repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
go-telegram-bot-api/telegram-bot-api
bot.go
decodeAPIResponse
func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) { if !bot.Debug { dec := json.NewDecoder(responseBody) err = dec.Decode(resp) return } // if debug, read reponse body data, err := ioutil.ReadAll(responseBody) if err != nil { return } err = json.Unmarshal(data, resp) if err != nil { return } return data, nil }
go
func (bot *BotAPI) decodeAPIResponse(responseBody io.Reader, resp *APIResponse) (_ []byte, err error) { if !bot.Debug { dec := json.NewDecoder(responseBody) err = dec.Decode(resp) return } // if debug, read reponse body data, err := ioutil.ReadAll(responseBody) if err != nil { return } err = json.Unmarshal(data, resp) if err != nil { return } return data, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "decodeAPIResponse", "(", "responseBody", "io", ".", "Reader", ",", "resp", "*", "APIResponse", ")", "(", "_", "[", "]", "byte", ",", "err", "error", ")", "{", "if", "!", "bot", ".", "Debug", "{", "dec", ":=", "json", ".", "NewDecoder", "(", "responseBody", ")", "\n", "err", "=", "dec", ".", "Decode", "(", "resp", ")", "\n", "return", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "responseBody", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "data", ",", "nil", "\n", "}" ]
// decodeAPIResponse decode response and return slice of bytes if debug enabled. // If debug disabled, just decode http.Response.Body stream to APIResponse struct // for efficient memory usage
[ "decodeAPIResponse", "decode", "response", "and", "return", "slice", "of", "bytes", "if", "debug", "enabled", ".", "If", "debug", "disabled", "just", "decode", "http", ".", "Response", ".", "Body", "stream", "to", "APIResponse", "struct", "for", "efficient", "memory", "usage" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L96-L115
train
go-telegram-bot-api/telegram-bot-api
bot.go
makeMessageRequest
func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) { resp, err := bot.MakeRequest(endpoint, params) if err != nil { return Message{}, err } var message Message json.Unmarshal(resp.Result, &message) bot.debugLog(endpoint, params, message) return message, nil }
go
func (bot *BotAPI) makeMessageRequest(endpoint string, params url.Values) (Message, error) { resp, err := bot.MakeRequest(endpoint, params) if err != nil { return Message{}, err } var message Message json.Unmarshal(resp.Result, &message) bot.debugLog(endpoint, params, message) return message, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "makeMessageRequest", "(", "endpoint", "string", ",", "params", "url", ".", "Values", ")", "(", "Message", ",", "error", ")", "{", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "endpoint", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Message", "{", "}", ",", "err", "\n", "}", "\n", "var", "message", "Message", "\n", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "message", ")", "\n", "bot", ".", "debugLog", "(", "endpoint", ",", "params", ",", "message", ")", "\n", "return", "message", ",", "nil", "\n", "}" ]
// makeMessageRequest makes a request to a method that returns a Message.
[ "makeMessageRequest", "makes", "a", "request", "to", "a", "method", "that", "returns", "a", "Message", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L118-L130
train
go-telegram-bot-api/telegram-bot-api
bot.go
UploadFile
func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) { ms := multipartstreamer.New() switch f := file.(type) { case string: ms.WriteFields(params) fileHandle, err := os.Open(f) if err != nil { return APIResponse{}, err } defer fileHandle.Close() fi, err := os.Stat(f) if err != nil { return APIResponse{}, err } ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle) case FileBytes: ms.WriteFields(params) buf := bytes.NewBuffer(f.Bytes) ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf) case FileReader: ms.WriteFields(params) if f.Size != -1 { ms.WriteReader(fieldname, f.Name, f.Size, f.Reader) break } data, err := ioutil.ReadAll(f.Reader) if err != nil { return APIResponse{}, err } buf := bytes.NewBuffer(data) ms.WriteReader(fieldname, f.Name, int64(len(data)), buf) case url.URL: params[fieldname] = f.String() ms.WriteFields(params) default: return APIResponse{}, errors.New(ErrBadFileType) } method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint) req, err := http.NewRequest("POST", method, nil) if err != nil { return APIResponse{}, err } ms.SetupRequest(req) res, err := bot.Client.Do(req) if err != nil { return APIResponse{}, err } defer res.Body.Close() bytes, err := ioutil.ReadAll(res.Body) if err != nil { return APIResponse{}, err } if bot.Debug { log.Println(string(bytes)) } var apiResp APIResponse err = json.Unmarshal(bytes, &apiResp) if err != nil { return APIResponse{}, err } if !apiResp.Ok { return APIResponse{}, errors.New(apiResp.Description) } return apiResp, nil }
go
func (bot *BotAPI) UploadFile(endpoint string, params map[string]string, fieldname string, file interface{}) (APIResponse, error) { ms := multipartstreamer.New() switch f := file.(type) { case string: ms.WriteFields(params) fileHandle, err := os.Open(f) if err != nil { return APIResponse{}, err } defer fileHandle.Close() fi, err := os.Stat(f) if err != nil { return APIResponse{}, err } ms.WriteReader(fieldname, fileHandle.Name(), fi.Size(), fileHandle) case FileBytes: ms.WriteFields(params) buf := bytes.NewBuffer(f.Bytes) ms.WriteReader(fieldname, f.Name, int64(len(f.Bytes)), buf) case FileReader: ms.WriteFields(params) if f.Size != -1 { ms.WriteReader(fieldname, f.Name, f.Size, f.Reader) break } data, err := ioutil.ReadAll(f.Reader) if err != nil { return APIResponse{}, err } buf := bytes.NewBuffer(data) ms.WriteReader(fieldname, f.Name, int64(len(data)), buf) case url.URL: params[fieldname] = f.String() ms.WriteFields(params) default: return APIResponse{}, errors.New(ErrBadFileType) } method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint) req, err := http.NewRequest("POST", method, nil) if err != nil { return APIResponse{}, err } ms.SetupRequest(req) res, err := bot.Client.Do(req) if err != nil { return APIResponse{}, err } defer res.Body.Close() bytes, err := ioutil.ReadAll(res.Body) if err != nil { return APIResponse{}, err } if bot.Debug { log.Println(string(bytes)) } var apiResp APIResponse err = json.Unmarshal(bytes, &apiResp) if err != nil { return APIResponse{}, err } if !apiResp.Ok { return APIResponse{}, errors.New(apiResp.Description) } return apiResp, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "UploadFile", "(", "endpoint", "string", ",", "params", "map", "[", "string", "]", "string", ",", "fieldname", "string", ",", "file", "interface", "{", "}", ")", "(", "APIResponse", ",", "error", ")", "{", "ms", ":=", "multipartstreamer", ".", "New", "(", ")", "\n", "switch", "f", ":=", "file", ".", "(", "type", ")", "{", "case", "string", ":", "ms", ".", "WriteFields", "(", "params", ")", "\n", "fileHandle", ",", "err", ":=", "os", ".", "Open", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "defer", "fileHandle", ".", "Close", "(", ")", "\n", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "ms", ".", "WriteReader", "(", "fieldname", ",", "fileHandle", ".", "Name", "(", ")", ",", "fi", ".", "Size", "(", ")", ",", "fileHandle", ")", "\n", "case", "FileBytes", ":", "ms", ".", "WriteFields", "(", "params", ")", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "f", ".", "Bytes", ")", "\n", "ms", ".", "WriteReader", "(", "fieldname", ",", "f", ".", "Name", ",", "int64", "(", "len", "(", "f", ".", "Bytes", ")", ")", ",", "buf", ")", "\n", "case", "FileReader", ":", "ms", ".", "WriteFields", "(", "params", ")", "\n", "if", "f", ".", "Size", "!=", "-", "1", "{", "ms", ".", "WriteReader", "(", "fieldname", ",", "f", ".", "Name", ",", "f", ".", "Size", ",", "f", ".", "Reader", ")", "\n", "break", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "data", ")", "\n", "ms", ".", "WriteReader", "(", "fieldname", ",", "f", ".", "Name", ",", "int64", "(", "len", "(", "data", ")", ")", ",", "buf", ")", "\n", "case", "url", ".", "URL", ":", "params", "[", "fieldname", "]", "=", "f", ".", "String", "(", ")", "\n", "ms", ".", "WriteFields", "(", "params", ")", "\n", "default", ":", "return", "APIResponse", "{", "}", ",", "errors", ".", "New", "(", "ErrBadFileType", ")", "\n", "}", "\n", "method", ":=", "fmt", ".", "Sprintf", "(", "APIEndpoint", ",", "bot", ".", "Token", ",", "endpoint", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"POST\"", ",", "method", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "ms", ".", "SetupRequest", "(", "req", ")", "\n", "res", ",", "err", ":=", "bot", ".", "Client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "bytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "if", "bot", ".", "Debug", "{", "log", ".", "Println", "(", "string", "(", "bytes", ")", ")", "\n", "}", "\n", "var", "apiResp", "APIResponse", "\n", "err", "=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "apiResp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "if", "!", "apiResp", ".", "Ok", "{", "return", "APIResponse", "{", "}", ",", "errors", ".", "New", "(", "apiResp", ".", "Description", ")", "\n", "}", "\n", "return", "apiResp", ",", "nil", "\n", "}" ]
// UploadFile makes a request to the API with a file. // // Requires the parameter to hold the file not be in the params. // File should be a string to a file path, a FileBytes struct, // a FileReader struct, or a url.URL. // // Note that if your FileReader has a size set to -1, it will read // the file into memory to calculate a size.
[ "UploadFile", "makes", "a", "request", "to", "the", "API", "with", "a", "file", ".", "Requires", "the", "parameter", "to", "hold", "the", "file", "not", "be", "in", "the", "params", ".", "File", "should", "be", "a", "string", "to", "a", "file", "path", "a", "FileBytes", "struct", "a", "FileReader", "struct", "or", "a", "url", ".", "URL", ".", "Note", "that", "if", "your", "FileReader", "has", "a", "size", "set", "to", "-", "1", "it", "will", "read", "the", "file", "into", "memory", "to", "calculate", "a", "size", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L140-L225
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetFileDirectURL
func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) { file, err := bot.GetFile(FileConfig{fileID}) if err != nil { return "", err } return file.Link(bot.Token), nil }
go
func (bot *BotAPI) GetFileDirectURL(fileID string) (string, error) { file, err := bot.GetFile(FileConfig{fileID}) if err != nil { return "", err } return file.Link(bot.Token), nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetFileDirectURL", "(", "fileID", "string", ")", "(", "string", ",", "error", ")", "{", "file", ",", "err", ":=", "bot", ".", "GetFile", "(", "FileConfig", "{", "fileID", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "file", ".", "Link", "(", "bot", ".", "Token", ")", ",", "nil", "\n", "}" ]
// GetFileDirectURL returns direct URL to file // // It requires the FileID.
[ "GetFileDirectURL", "returns", "direct", "URL", "to", "file", "It", "requires", "the", "FileID", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L230-L238
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetMe
func (bot *BotAPI) GetMe() (User, error) { resp, err := bot.MakeRequest("getMe", nil) if err != nil { return User{}, err } var user User json.Unmarshal(resp.Result, &user) bot.debugLog("getMe", nil, user) return user, nil }
go
func (bot *BotAPI) GetMe() (User, error) { resp, err := bot.MakeRequest("getMe", nil) if err != nil { return User{}, err } var user User json.Unmarshal(resp.Result, &user) bot.debugLog("getMe", nil, user) return user, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetMe", "(", ")", "(", "User", ",", "error", ")", "{", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getMe\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "User", "{", "}", ",", "err", "\n", "}", "\n", "var", "user", "User", "\n", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "user", ")", "\n", "bot", ".", "debugLog", "(", "\"getMe\"", ",", "nil", ",", "user", ")", "\n", "return", "user", ",", "nil", "\n", "}" ]
// GetMe fetches the currently authenticated bot. // // This method is called upon creation to validate the token, // and so you may get this data from BotAPI.Self without the need for // another request.
[ "GetMe", "fetches", "the", "currently", "authenticated", "bot", ".", "This", "method", "is", "called", "upon", "creation", "to", "validate", "the", "token", "and", "so", "you", "may", "get", "this", "data", "from", "BotAPI", ".", "Self", "without", "the", "need", "for", "another", "request", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L245-L257
train
go-telegram-bot-api/telegram-bot-api
bot.go
IsMessageToMe
func (bot *BotAPI) IsMessageToMe(message Message) bool { return strings.Contains(message.Text, "@"+bot.Self.UserName) }
go
func (bot *BotAPI) IsMessageToMe(message Message) bool { return strings.Contains(message.Text, "@"+bot.Self.UserName) }
[ "func", "(", "bot", "*", "BotAPI", ")", "IsMessageToMe", "(", "message", "Message", ")", "bool", "{", "return", "strings", ".", "Contains", "(", "message", ".", "Text", ",", "\"@\"", "+", "bot", ".", "Self", ".", "UserName", ")", "\n", "}" ]
// IsMessageToMe returns true if message directed to this bot. // // It requires the Message.
[ "IsMessageToMe", "returns", "true", "if", "message", "directed", "to", "this", "bot", ".", "It", "requires", "the", "Message", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L262-L264
train
go-telegram-bot-api/telegram-bot-api
bot.go
Send
func (bot *BotAPI) Send(c Chattable) (Message, error) { switch c.(type) { case Fileable: return bot.sendFile(c.(Fileable)) default: return bot.sendChattable(c) } }
go
func (bot *BotAPI) Send(c Chattable) (Message, error) { switch c.(type) { case Fileable: return bot.sendFile(c.(Fileable)) default: return bot.sendChattable(c) } }
[ "func", "(", "bot", "*", "BotAPI", ")", "Send", "(", "c", "Chattable", ")", "(", "Message", ",", "error", ")", "{", "switch", "c", ".", "(", "type", ")", "{", "case", "Fileable", ":", "return", "bot", ".", "sendFile", "(", "c", ".", "(", "Fileable", ")", ")", "\n", "default", ":", "return", "bot", ".", "sendChattable", "(", "c", ")", "\n", "}", "\n", "}" ]
// Send will send a Chattable item to Telegram. // // It requires the Chattable to send.
[ "Send", "will", "send", "a", "Chattable", "item", "to", "Telegram", ".", "It", "requires", "the", "Chattable", "to", "send", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L269-L276
train
go-telegram-bot-api/telegram-bot-api
bot.go
debugLog
func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) { if bot.Debug { log.Printf("%s req : %+v\n", context, v) log.Printf("%s resp: %+v\n", context, message) } }
go
func (bot *BotAPI) debugLog(context string, v url.Values, message interface{}) { if bot.Debug { log.Printf("%s req : %+v\n", context, v) log.Printf("%s resp: %+v\n", context, message) } }
[ "func", "(", "bot", "*", "BotAPI", ")", "debugLog", "(", "context", "string", ",", "v", "url", ".", "Values", ",", "message", "interface", "{", "}", ")", "{", "if", "bot", ".", "Debug", "{", "log", ".", "Printf", "(", "\"%s req : %+v\\n\"", ",", "\\n", ",", "context", ")", "\n", "v", "\n", "}", "\n", "}" ]
// debugLog checks if the bot is currently running in debug mode, and if // so will display information about the request and response in the // debug log.
[ "debugLog", "checks", "if", "the", "bot", "is", "currently", "running", "in", "debug", "mode", "and", "if", "so", "will", "display", "information", "about", "the", "request", "and", "response", "in", "the", "debug", "log", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L281-L286
train
go-telegram-bot-api/telegram-bot-api
bot.go
sendExisting
func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) { v, err := config.values() if err != nil { return Message{}, err } message, err := bot.makeMessageRequest(method, v) if err != nil { return Message{}, err } return message, nil }
go
func (bot *BotAPI) sendExisting(method string, config Fileable) (Message, error) { v, err := config.values() if err != nil { return Message{}, err } message, err := bot.makeMessageRequest(method, v) if err != nil { return Message{}, err } return message, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "sendExisting", "(", "method", "string", ",", "config", "Fileable", ")", "(", "Message", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Message", "{", "}", ",", "err", "\n", "}", "\n", "message", ",", "err", ":=", "bot", ".", "makeMessageRequest", "(", "method", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Message", "{", "}", ",", "err", "\n", "}", "\n", "return", "message", ",", "nil", "\n", "}" ]
// sendExisting will send a Message with an existing file to Telegram.
[ "sendExisting", "will", "send", "a", "Message", "with", "an", "existing", "file", "to", "Telegram", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L289-L302
train
go-telegram-bot-api/telegram-bot-api
bot.go
uploadAndSend
func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) { params, err := config.params() if err != nil { return Message{}, err } file := config.getFile() resp, err := bot.UploadFile(method, params, config.name(), file) if err != nil { return Message{}, err } var message Message json.Unmarshal(resp.Result, &message) bot.debugLog(method, nil, message) return message, nil }
go
func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) { params, err := config.params() if err != nil { return Message{}, err } file := config.getFile() resp, err := bot.UploadFile(method, params, config.name(), file) if err != nil { return Message{}, err } var message Message json.Unmarshal(resp.Result, &message) bot.debugLog(method, nil, message) return message, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "uploadAndSend", "(", "method", "string", ",", "config", "Fileable", ")", "(", "Message", ",", "error", ")", "{", "params", ",", "err", ":=", "config", ".", "params", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Message", "{", "}", ",", "err", "\n", "}", "\n", "file", ":=", "config", ".", "getFile", "(", ")", "\n", "resp", ",", "err", ":=", "bot", ".", "UploadFile", "(", "method", ",", "params", ",", "config", ".", "name", "(", ")", ",", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Message", "{", "}", ",", "err", "\n", "}", "\n", "var", "message", "Message", "\n", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "message", ")", "\n", "bot", ".", "debugLog", "(", "method", ",", "nil", ",", "message", ")", "\n", "return", "message", ",", "nil", "\n", "}" ]
// uploadAndSend will send a Message with a new file to Telegram.
[ "uploadAndSend", "will", "send", "a", "Message", "with", "a", "new", "file", "to", "Telegram", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L305-L324
train
go-telegram-bot-api/telegram-bot-api
bot.go
sendFile
func (bot *BotAPI) sendFile(config Fileable) (Message, error) { if config.useExistingFile() { return bot.sendExisting(config.method(), config) } return bot.uploadAndSend(config.method(), config) }
go
func (bot *BotAPI) sendFile(config Fileable) (Message, error) { if config.useExistingFile() { return bot.sendExisting(config.method(), config) } return bot.uploadAndSend(config.method(), config) }
[ "func", "(", "bot", "*", "BotAPI", ")", "sendFile", "(", "config", "Fileable", ")", "(", "Message", ",", "error", ")", "{", "if", "config", ".", "useExistingFile", "(", ")", "{", "return", "bot", ".", "sendExisting", "(", "config", ".", "method", "(", ")", ",", "config", ")", "\n", "}", "\n", "return", "bot", ".", "uploadAndSend", "(", "config", ".", "method", "(", ")", ",", "config", ")", "\n", "}" ]
// sendFile determines if the file is using an existing file or uploading // a new file, then sends it as needed.
[ "sendFile", "determines", "if", "the", "file", "is", "using", "an", "existing", "file", "or", "uploading", "a", "new", "file", "then", "sends", "it", "as", "needed", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L328-L334
train
go-telegram-bot-api/telegram-bot-api
bot.go
sendChattable
func (bot *BotAPI) sendChattable(config Chattable) (Message, error) { v, err := config.values() if err != nil { return Message{}, err } message, err := bot.makeMessageRequest(config.method(), v) if err != nil { return Message{}, err } return message, nil }
go
func (bot *BotAPI) sendChattable(config Chattable) (Message, error) { v, err := config.values() if err != nil { return Message{}, err } message, err := bot.makeMessageRequest(config.method(), v) if err != nil { return Message{}, err } return message, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "sendChattable", "(", "config", "Chattable", ")", "(", "Message", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Message", "{", "}", ",", "err", "\n", "}", "\n", "message", ",", "err", ":=", "bot", ".", "makeMessageRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Message", "{", "}", ",", "err", "\n", "}", "\n", "return", "message", ",", "nil", "\n", "}" ]
// sendChattable sends a Chattable.
[ "sendChattable", "sends", "a", "Chattable", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L337-L350
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetUserProfilePhotos
func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) { v := url.Values{} v.Add("user_id", strconv.Itoa(config.UserID)) if config.Offset != 0 { v.Add("offset", strconv.Itoa(config.Offset)) } if config.Limit != 0 { v.Add("limit", strconv.Itoa(config.Limit)) } resp, err := bot.MakeRequest("getUserProfilePhotos", v) if err != nil { return UserProfilePhotos{}, err } var profilePhotos UserProfilePhotos json.Unmarshal(resp.Result, &profilePhotos) bot.debugLog("GetUserProfilePhoto", v, profilePhotos) return profilePhotos, nil }
go
func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) { v := url.Values{} v.Add("user_id", strconv.Itoa(config.UserID)) if config.Offset != 0 { v.Add("offset", strconv.Itoa(config.Offset)) } if config.Limit != 0 { v.Add("limit", strconv.Itoa(config.Limit)) } resp, err := bot.MakeRequest("getUserProfilePhotos", v) if err != nil { return UserProfilePhotos{}, err } var profilePhotos UserProfilePhotos json.Unmarshal(resp.Result, &profilePhotos) bot.debugLog("GetUserProfilePhoto", v, profilePhotos) return profilePhotos, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetUserProfilePhotos", "(", "config", "UserProfilePhotosConfig", ")", "(", "UserProfilePhotos", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "v", ".", "Add", "(", "\"user_id\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n", "if", "config", ".", "Offset", "!=", "0", "{", "v", ".", "Add", "(", "\"offset\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Offset", ")", ")", "\n", "}", "\n", "if", "config", ".", "Limit", "!=", "0", "{", "v", ".", "Add", "(", "\"limit\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Limit", ")", ")", "\n", "}", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getUserProfilePhotos\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "UserProfilePhotos", "{", "}", ",", "err", "\n", "}", "\n", "var", "profilePhotos", "UserProfilePhotos", "\n", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "profilePhotos", ")", "\n", "bot", ".", "debugLog", "(", "\"GetUserProfilePhoto\"", ",", "v", ",", "profilePhotos", ")", "\n", "return", "profilePhotos", ",", "nil", "\n", "}" ]
// GetUserProfilePhotos gets a user's profile photos. // // It requires UserID. // Offset and Limit are optional.
[ "GetUserProfilePhotos", "gets", "a", "user", "s", "profile", "photos", ".", "It", "requires", "UserID", ".", "Offset", "and", "Limit", "are", "optional", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L356-L377
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetFile
func (bot *BotAPI) GetFile(config FileConfig) (File, error) { v := url.Values{} v.Add("file_id", config.FileID) resp, err := bot.MakeRequest("getFile", v) if err != nil { return File{}, err } var file File json.Unmarshal(resp.Result, &file) bot.debugLog("GetFile", v, file) return file, nil }
go
func (bot *BotAPI) GetFile(config FileConfig) (File, error) { v := url.Values{} v.Add("file_id", config.FileID) resp, err := bot.MakeRequest("getFile", v) if err != nil { return File{}, err } var file File json.Unmarshal(resp.Result, &file) bot.debugLog("GetFile", v, file) return file, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetFile", "(", "config", "FileConfig", ")", "(", "File", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "v", ".", "Add", "(", "\"file_id\"", ",", "config", ".", "FileID", ")", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getFile\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "File", "{", "}", ",", "err", "\n", "}", "\n", "var", "file", "File", "\n", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "file", ")", "\n", "bot", ".", "debugLog", "(", "\"GetFile\"", ",", "v", ",", "file", ")", "\n", "return", "file", ",", "nil", "\n", "}" ]
// GetFile returns a File which can download a file from Telegram. // // Requires FileID.
[ "GetFile", "returns", "a", "File", "which", "can", "download", "a", "file", "from", "Telegram", ".", "Requires", "FileID", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L382-L397
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetUpdates
func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { v := url.Values{} if config.Offset != 0 { v.Add("offset", strconv.Itoa(config.Offset)) } if config.Limit > 0 { v.Add("limit", strconv.Itoa(config.Limit)) } if config.Timeout > 0 { v.Add("timeout", strconv.Itoa(config.Timeout)) } resp, err := bot.MakeRequest("getUpdates", v) if err != nil { return []Update{}, err } var updates []Update json.Unmarshal(resp.Result, &updates) bot.debugLog("getUpdates", v, updates) return updates, nil }
go
func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error) { v := url.Values{} if config.Offset != 0 { v.Add("offset", strconv.Itoa(config.Offset)) } if config.Limit > 0 { v.Add("limit", strconv.Itoa(config.Limit)) } if config.Timeout > 0 { v.Add("timeout", strconv.Itoa(config.Timeout)) } resp, err := bot.MakeRequest("getUpdates", v) if err != nil { return []Update{}, err } var updates []Update json.Unmarshal(resp.Result, &updates) bot.debugLog("getUpdates", v, updates) return updates, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetUpdates", "(", "config", "UpdateConfig", ")", "(", "[", "]", "Update", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "Offset", "!=", "0", "{", "v", ".", "Add", "(", "\"offset\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Offset", ")", ")", "\n", "}", "\n", "if", "config", ".", "Limit", ">", "0", "{", "v", ".", "Add", "(", "\"limit\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Limit", ")", ")", "\n", "}", "\n", "if", "config", ".", "Timeout", ">", "0", "{", "v", ".", "Add", "(", "\"timeout\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Timeout", ")", ")", "\n", "}", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getUpdates\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "Update", "{", "}", ",", "err", "\n", "}", "\n", "var", "updates", "[", "]", "Update", "\n", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "updates", ")", "\n", "bot", ".", "debugLog", "(", "\"getUpdates\"", ",", "v", ",", "updates", ")", "\n", "return", "updates", ",", "nil", "\n", "}" ]
// GetUpdates fetches updates. // If a WebHook is set, this will not return any data! // // Offset, Limit, and Timeout are optional. // To avoid stale items, set Offset to one higher than the previous item. // Set Timeout to a large number to reduce requests so you can get updates // instantly instead of having to wait between requests.
[ "GetUpdates", "fetches", "updates", ".", "If", "a", "WebHook", "is", "set", "this", "will", "not", "return", "any", "data!", "Offset", "Limit", "and", "Timeout", "are", "optional", ".", "To", "avoid", "stale", "items", "set", "Offset", "to", "one", "higher", "than", "the", "previous", "item", ".", "Set", "Timeout", "to", "a", "large", "number", "to", "reduce", "requests", "so", "you", "can", "get", "updates", "instantly", "instead", "of", "having", "to", "wait", "between", "requests", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L406-L429
train
go-telegram-bot-api/telegram-bot-api
bot.go
SetWebhook
func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) { if config.Certificate == nil { v := url.Values{} v.Add("url", config.URL.String()) if config.MaxConnections != 0 { v.Add("max_connections", strconv.Itoa(config.MaxConnections)) } return bot.MakeRequest("setWebhook", v) } params := make(map[string]string) params["url"] = config.URL.String() if config.MaxConnections != 0 { params["max_connections"] = strconv.Itoa(config.MaxConnections) } resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate) if err != nil { return APIResponse{}, err } return resp, nil }
go
func (bot *BotAPI) SetWebhook(config WebhookConfig) (APIResponse, error) { if config.Certificate == nil { v := url.Values{} v.Add("url", config.URL.String()) if config.MaxConnections != 0 { v.Add("max_connections", strconv.Itoa(config.MaxConnections)) } return bot.MakeRequest("setWebhook", v) } params := make(map[string]string) params["url"] = config.URL.String() if config.MaxConnections != 0 { params["max_connections"] = strconv.Itoa(config.MaxConnections) } resp, err := bot.UploadFile("setWebhook", params, "certificate", config.Certificate) if err != nil { return APIResponse{}, err } return resp, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "SetWebhook", "(", "config", "WebhookConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "if", "config", ".", "Certificate", "==", "nil", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "v", ".", "Add", "(", "\"url\"", ",", "config", ".", "URL", ".", "String", "(", ")", ")", "\n", "if", "config", ".", "MaxConnections", "!=", "0", "{", "v", ".", "Add", "(", "\"max_connections\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "MaxConnections", ")", ")", "\n", "}", "\n", "return", "bot", ".", "MakeRequest", "(", "\"setWebhook\"", ",", "v", ")", "\n", "}", "\n", "params", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "params", "[", "\"url\"", "]", "=", "config", ".", "URL", ".", "String", "(", ")", "\n", "if", "config", ".", "MaxConnections", "!=", "0", "{", "params", "[", "\"max_connections\"", "]", "=", "strconv", ".", "Itoa", "(", "config", ".", "MaxConnections", ")", "\n", "}", "\n", "resp", ",", "err", ":=", "bot", ".", "UploadFile", "(", "\"setWebhook\"", ",", "params", ",", "\"certificate\"", ",", "config", ".", "Certificate", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// SetWebhook sets a webhook. // // If this is set, GetUpdates will not get any data! // // If you do not have a legitimate TLS certificate, you need to include // your self signed certificate with the config.
[ "SetWebhook", "sets", "a", "webhook", ".", "If", "this", "is", "set", "GetUpdates", "will", "not", "get", "any", "data!", "If", "you", "do", "not", "have", "a", "legitimate", "TLS", "certificate", "you", "need", "to", "include", "your", "self", "signed", "certificate", "with", "the", "config", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L442-L466
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetWebhookInfo
func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { resp, err := bot.MakeRequest("getWebhookInfo", url.Values{}) if err != nil { return WebhookInfo{}, err } var info WebhookInfo err = json.Unmarshal(resp.Result, &info) return info, err }
go
func (bot *BotAPI) GetWebhookInfo() (WebhookInfo, error) { resp, err := bot.MakeRequest("getWebhookInfo", url.Values{}) if err != nil { return WebhookInfo{}, err } var info WebhookInfo err = json.Unmarshal(resp.Result, &info) return info, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetWebhookInfo", "(", ")", "(", "WebhookInfo", ",", "error", ")", "{", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getWebhookInfo\"", ",", "url", ".", "Values", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "WebhookInfo", "{", "}", ",", "err", "\n", "}", "\n", "var", "info", "WebhookInfo", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "info", ")", "\n", "return", "info", ",", "err", "\n", "}" ]
// GetWebhookInfo allows you to fetch information about a webhook and if // one currently is set, along with pending update count and error messages.
[ "GetWebhookInfo", "allows", "you", "to", "fetch", "information", "about", "a", "webhook", "and", "if", "one", "currently", "is", "set", "along", "with", "pending", "update", "count", "and", "error", "messages", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L470-L480
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetUpdatesChan
func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) { ch := make(chan Update, bot.Buffer) go func() { for { select { case <-bot.shutdownChannel: return default: } updates, err := bot.GetUpdates(config) if err != nil { log.Println(err) log.Println("Failed to get updates, retrying in 3 seconds...") time.Sleep(time.Second * 3) continue } for _, update := range updates { if update.UpdateID >= config.Offset { config.Offset = update.UpdateID + 1 ch <- update } } } }() return ch, nil }
go
func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error) { ch := make(chan Update, bot.Buffer) go func() { for { select { case <-bot.shutdownChannel: return default: } updates, err := bot.GetUpdates(config) if err != nil { log.Println(err) log.Println("Failed to get updates, retrying in 3 seconds...") time.Sleep(time.Second * 3) continue } for _, update := range updates { if update.UpdateID >= config.Offset { config.Offset = update.UpdateID + 1 ch <- update } } } }() return ch, nil }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetUpdatesChan", "(", "config", "UpdateConfig", ")", "(", "UpdatesChannel", ",", "error", ")", "{", "ch", ":=", "make", "(", "chan", "Update", ",", "bot", ".", "Buffer", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "bot", ".", "shutdownChannel", ":", "return", "\n", "default", ":", "}", "\n", "updates", ",", "err", ":=", "bot", ".", "GetUpdates", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Println", "(", "err", ")", "\n", "log", ".", "Println", "(", "\"Failed to get updates, retrying in 3 seconds...\"", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Second", "*", "3", ")", "\n", "continue", "\n", "}", "\n", "for", "_", ",", "update", ":=", "range", "updates", "{", "if", "update", ".", "UpdateID", ">=", "config", ".", "Offset", "{", "config", ".", "Offset", "=", "update", ".", "UpdateID", "+", "1", "\n", "ch", "<-", "update", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "ch", ",", "nil", "\n", "}" ]
// GetUpdatesChan starts and returns a channel for getting updates.
[ "GetUpdatesChan", "starts", "and", "returns", "a", "channel", "for", "getting", "updates", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L483-L513
train
go-telegram-bot-api/telegram-bot-api
bot.go
StopReceivingUpdates
func (bot *BotAPI) StopReceivingUpdates() { if bot.Debug { log.Println("Stopping the update receiver routine...") } close(bot.shutdownChannel) }
go
func (bot *BotAPI) StopReceivingUpdates() { if bot.Debug { log.Println("Stopping the update receiver routine...") } close(bot.shutdownChannel) }
[ "func", "(", "bot", "*", "BotAPI", ")", "StopReceivingUpdates", "(", ")", "{", "if", "bot", ".", "Debug", "{", "log", ".", "Println", "(", "\"Stopping the update receiver routine...\"", ")", "\n", "}", "\n", "close", "(", "bot", ".", "shutdownChannel", ")", "\n", "}" ]
// StopReceivingUpdates stops the go routine which receives updates
[ "StopReceivingUpdates", "stops", "the", "go", "routine", "which", "receives", "updates" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L516-L521
train
go-telegram-bot-api/telegram-bot-api
bot.go
ListenForWebhook
func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel { ch := make(chan Update, bot.Buffer) http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { bytes, _ := ioutil.ReadAll(r.Body) r.Body.Close() var update Update json.Unmarshal(bytes, &update) ch <- update }) return ch }
go
func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel { ch := make(chan Update, bot.Buffer) http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { bytes, _ := ioutil.ReadAll(r.Body) r.Body.Close() var update Update json.Unmarshal(bytes, &update) ch <- update }) return ch }
[ "func", "(", "bot", "*", "BotAPI", ")", "ListenForWebhook", "(", "pattern", "string", ")", "UpdatesChannel", "{", "ch", ":=", "make", "(", "chan", "Update", ",", "bot", ".", "Buffer", ")", "\n", "http", ".", "HandleFunc", "(", "pattern", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "bytes", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "r", ".", "Body", ".", "Close", "(", ")", "\n", "var", "update", "Update", "\n", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "update", ")", "\n", "ch", "<-", "update", "\n", "}", ")", "\n", "return", "ch", "\n", "}" ]
// ListenForWebhook registers a http handler for a webhook.
[ "ListenForWebhook", "registers", "a", "http", "handler", "for", "a", "webhook", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L524-L538
train
go-telegram-bot-api/telegram-bot-api
bot.go
AnswerInlineQuery
func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) { v := url.Values{} v.Add("inline_query_id", config.InlineQueryID) v.Add("cache_time", strconv.Itoa(config.CacheTime)) v.Add("is_personal", strconv.FormatBool(config.IsPersonal)) v.Add("next_offset", config.NextOffset) data, err := json.Marshal(config.Results) if err != nil { return APIResponse{}, err } v.Add("results", string(data)) v.Add("switch_pm_text", config.SwitchPMText) v.Add("switch_pm_parameter", config.SwitchPMParameter) bot.debugLog("answerInlineQuery", v, nil) return bot.MakeRequest("answerInlineQuery", v) }
go
func (bot *BotAPI) AnswerInlineQuery(config InlineConfig) (APIResponse, error) { v := url.Values{} v.Add("inline_query_id", config.InlineQueryID) v.Add("cache_time", strconv.Itoa(config.CacheTime)) v.Add("is_personal", strconv.FormatBool(config.IsPersonal)) v.Add("next_offset", config.NextOffset) data, err := json.Marshal(config.Results) if err != nil { return APIResponse{}, err } v.Add("results", string(data)) v.Add("switch_pm_text", config.SwitchPMText) v.Add("switch_pm_parameter", config.SwitchPMParameter) bot.debugLog("answerInlineQuery", v, nil) return bot.MakeRequest("answerInlineQuery", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "AnswerInlineQuery", "(", "config", "InlineConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "v", ".", "Add", "(", "\"inline_query_id\"", ",", "config", ".", "InlineQueryID", ")", "\n", "v", ".", "Add", "(", "\"cache_time\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "CacheTime", ")", ")", "\n", "v", ".", "Add", "(", "\"is_personal\"", ",", "strconv", ".", "FormatBool", "(", "config", ".", "IsPersonal", ")", ")", "\n", "v", ".", "Add", "(", "\"next_offset\"", ",", "config", ".", "NextOffset", ")", "\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "config", ".", "Results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"results\"", ",", "string", "(", "data", ")", ")", "\n", "v", ".", "Add", "(", "\"switch_pm_text\"", ",", "config", ".", "SwitchPMText", ")", "\n", "v", ".", "Add", "(", "\"switch_pm_parameter\"", ",", "config", ".", "SwitchPMParameter", ")", "\n", "bot", ".", "debugLog", "(", "\"answerInlineQuery\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"answerInlineQuery\"", ",", "v", ")", "\n", "}" ]
// AnswerInlineQuery sends a response to an inline query. // // Note that you must respond to an inline query within 30 seconds.
[ "AnswerInlineQuery", "sends", "a", "response", "to", "an", "inline", "query", ".", "Note", "that", "you", "must", "respond", "to", "an", "inline", "query", "within", "30", "seconds", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L543-L561
train
go-telegram-bot-api/telegram-bot-api
bot.go
AnswerCallbackQuery
func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) { v := url.Values{} v.Add("callback_query_id", config.CallbackQueryID) if config.Text != "" { v.Add("text", config.Text) } v.Add("show_alert", strconv.FormatBool(config.ShowAlert)) if config.URL != "" { v.Add("url", config.URL) } v.Add("cache_time", strconv.Itoa(config.CacheTime)) bot.debugLog("answerCallbackQuery", v, nil) return bot.MakeRequest("answerCallbackQuery", v) }
go
func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) { v := url.Values{} v.Add("callback_query_id", config.CallbackQueryID) if config.Text != "" { v.Add("text", config.Text) } v.Add("show_alert", strconv.FormatBool(config.ShowAlert)) if config.URL != "" { v.Add("url", config.URL) } v.Add("cache_time", strconv.Itoa(config.CacheTime)) bot.debugLog("answerCallbackQuery", v, nil) return bot.MakeRequest("answerCallbackQuery", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "AnswerCallbackQuery", "(", "config", "CallbackConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "v", ".", "Add", "(", "\"callback_query_id\"", ",", "config", ".", "CallbackQueryID", ")", "\n", "if", "config", ".", "Text", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"text\"", ",", "config", ".", "Text", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"show_alert\"", ",", "strconv", ".", "FormatBool", "(", "config", ".", "ShowAlert", ")", ")", "\n", "if", "config", ".", "URL", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"url\"", ",", "config", ".", "URL", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"cache_time\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "CacheTime", ")", ")", "\n", "bot", ".", "debugLog", "(", "\"answerCallbackQuery\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"answerCallbackQuery\"", ",", "v", ")", "\n", "}" ]
// AnswerCallbackQuery sends a response to an inline query callback.
[ "AnswerCallbackQuery", "sends", "a", "response", "to", "an", "inline", "query", "callback", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L564-L580
train
go-telegram-bot-api/telegram-bot-api
bot.go
KickChatMember
func (bot *BotAPI) KickChatMember(config KickChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.UntilDate != 0 { v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) } bot.debugLog("kickChatMember", v, nil) return bot.MakeRequest("kickChatMember", v) }
go
func (bot *BotAPI) KickChatMember(config KickChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.UntilDate != 0 { v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) } bot.debugLog("kickChatMember", v, nil) return bot.MakeRequest("kickChatMember", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "KickChatMember", "(", "config", "KickChatMemberConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "==", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"user_id\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n", "if", "config", ".", "UntilDate", "!=", "0", "{", "v", ".", "Add", "(", "\"until_date\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "UntilDate", ",", "10", ")", ")", "\n", "}", "\n", "bot", ".", "debugLog", "(", "\"kickChatMember\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"kickChatMember\"", ",", "v", ")", "\n", "}" ]
// KickChatMember kicks a user from a chat. Note that this only will work // in supergroups, and requires the bot to be an admin. Also note they // will be unable to rejoin until they are unbanned.
[ "KickChatMember", "kicks", "a", "user", "from", "a", "chat", ".", "Note", "that", "this", "only", "will", "work", "in", "supergroups", "and", "requires", "the", "bot", "to", "be", "an", "admin", ".", "Also", "note", "they", "will", "be", "unable", "to", "rejoin", "until", "they", "are", "unbanned", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L585-L602
train
go-telegram-bot-api/telegram-bot-api
bot.go
LeaveChat
func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } bot.debugLog("leaveChat", v, nil) return bot.MakeRequest("leaveChat", v) }
go
func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } bot.debugLog("leaveChat", v, nil) return bot.MakeRequest("leaveChat", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "LeaveChat", "(", "config", "ChatConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "==", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "bot", ".", "debugLog", "(", "\"leaveChat\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"leaveChat\"", ",", "v", ")", "\n", "}" ]
// LeaveChat makes the bot leave the chat.
[ "LeaveChat", "makes", "the", "bot", "leave", "the", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L605-L617
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetChat
func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChat", v) if err != nil { return Chat{}, err } var chat Chat err = json.Unmarshal(resp.Result, &chat) bot.debugLog("getChat", v, chat) return chat, err }
go
func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChat", v) if err != nil { return Chat{}, err } var chat Chat err = json.Unmarshal(resp.Result, &chat) bot.debugLog("getChat", v, chat) return chat, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetChat", "(", "config", "ChatConfig", ")", "(", "Chat", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "==", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getChat\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Chat", "{", "}", ",", "err", "\n", "}", "\n", "var", "chat", "Chat", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "chat", ")", "\n", "bot", ".", "debugLog", "(", "\"getChat\"", ",", "v", ",", "chat", ")", "\n", "return", "chat", ",", "err", "\n", "}" ]
// GetChat gets information about a chat.
[ "GetChat", "gets", "information", "about", "a", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L620-L640
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetChatAdministrators
func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChatAdministrators", v) if err != nil { return []ChatMember{}, err } var members []ChatMember err = json.Unmarshal(resp.Result, &members) bot.debugLog("getChatAdministrators", v, members) return members, err }
go
func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChatAdministrators", v) if err != nil { return []ChatMember{}, err } var members []ChatMember err = json.Unmarshal(resp.Result, &members) bot.debugLog("getChatAdministrators", v, members) return members, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetChatAdministrators", "(", "config", "ChatConfig", ")", "(", "[", "]", "ChatMember", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "==", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getChatAdministrators\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "ChatMember", "{", "}", ",", "err", "\n", "}", "\n", "var", "members", "[", "]", "ChatMember", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "members", ")", "\n", "bot", ".", "debugLog", "(", "\"getChatAdministrators\"", ",", "v", ",", "members", ")", "\n", "return", "members", ",", "err", "\n", "}" ]
// GetChatAdministrators gets a list of administrators in the chat. // // If none have been appointed, only the creator will be returned. // Bots are not shown, even if they are an administrator.
[ "GetChatAdministrators", "gets", "a", "list", "of", "administrators", "in", "the", "chat", ".", "If", "none", "have", "been", "appointed", "only", "the", "creator", "will", "be", "returned", ".", "Bots", "are", "not", "shown", "even", "if", "they", "are", "an", "administrator", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L646-L666
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetChatMembersCount
func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChatMembersCount", v) if err != nil { return -1, err } var count int err = json.Unmarshal(resp.Result, &count) bot.debugLog("getChatMembersCount", v, count) return count, err }
go
func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChatMembersCount", v) if err != nil { return -1, err } var count int err = json.Unmarshal(resp.Result, &count) bot.debugLog("getChatMembersCount", v, count) return count, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetChatMembersCount", "(", "config", "ChatConfig", ")", "(", "int", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "==", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getChatMembersCount\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "var", "count", "int", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "count", ")", "\n", "bot", ".", "debugLog", "(", "\"getChatMembersCount\"", ",", "v", ",", "count", ")", "\n", "return", "count", ",", "err", "\n", "}" ]
// GetChatMembersCount gets the number of users in a chat.
[ "GetChatMembersCount", "gets", "the", "number", "of", "users", "in", "a", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L669-L689
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetChatMember
func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } v.Add("user_id", strconv.Itoa(config.UserID)) resp, err := bot.MakeRequest("getChatMember", v) if err != nil { return ChatMember{}, err } var member ChatMember err = json.Unmarshal(resp.Result, &member) bot.debugLog("getChatMember", v, member) return member, err }
go
func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } v.Add("user_id", strconv.Itoa(config.UserID)) resp, err := bot.MakeRequest("getChatMember", v) if err != nil { return ChatMember{}, err } var member ChatMember err = json.Unmarshal(resp.Result, &member) bot.debugLog("getChatMember", v, member) return member, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetChatMember", "(", "config", "ChatConfigWithUser", ")", "(", "ChatMember", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "==", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"user_id\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"getChatMember\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ChatMember", "{", "}", ",", "err", "\n", "}", "\n", "var", "member", "ChatMember", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "member", ")", "\n", "bot", ".", "debugLog", "(", "\"getChatMember\"", ",", "v", ",", "member", ")", "\n", "return", "member", ",", "err", "\n", "}" ]
// GetChatMember gets a specific chat member.
[ "GetChatMember", "gets", "a", "specific", "chat", "member", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L692-L713
train
go-telegram-bot-api/telegram-bot-api
bot.go
UnbanChatMember
func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) bot.debugLog("unbanChatMember", v, nil) return bot.MakeRequest("unbanChatMember", v) }
go
func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) bot.debugLog("unbanChatMember", v, nil) return bot.MakeRequest("unbanChatMember", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "UnbanChatMember", "(", "config", "ChatMemberConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "else", "if", "config", ".", "ChannelUsername", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "ChannelUsername", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"user_id\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n", "bot", ".", "debugLog", "(", "\"unbanChatMember\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"unbanChatMember\"", ",", "v", ")", "\n", "}" ]
// UnbanChatMember unbans a user from a chat. Note that this only will work // in supergroups and channels, and requires the bot to be an admin.
[ "UnbanChatMember", "unbans", "a", "user", "from", "a", "chat", ".", "Note", "that", "this", "only", "will", "work", "in", "supergroups", "and", "channels", "and", "requires", "the", "bot", "to", "be", "an", "admin", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L717-L732
train
go-telegram-bot-api/telegram-bot-api
bot.go
RestrictChatMember
func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.CanSendMessages != nil { v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages)) } if config.CanSendMediaMessages != nil { v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages)) } if config.CanSendOtherMessages != nil { v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages)) } if config.CanAddWebPagePreviews != nil { v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews)) } if config.UntilDate != 0 { v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) } bot.debugLog("restrictChatMember", v, nil) return bot.MakeRequest("restrictChatMember", v) }
go
func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.CanSendMessages != nil { v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages)) } if config.CanSendMediaMessages != nil { v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages)) } if config.CanSendOtherMessages != nil { v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages)) } if config.CanAddWebPagePreviews != nil { v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews)) } if config.UntilDate != 0 { v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) } bot.debugLog("restrictChatMember", v, nil) return bot.MakeRequest("restrictChatMember", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "RestrictChatMember", "(", "config", "RestrictChatMemberConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "else", "if", "config", ".", "ChannelUsername", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "ChannelUsername", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"user_id\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n", "if", "config", ".", "CanSendMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_send_messages\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanSendMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanSendMediaMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_send_media_messages\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanSendMediaMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanSendOtherMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_send_other_messages\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanSendOtherMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanAddWebPagePreviews", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_add_web_page_previews\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanAddWebPagePreviews", ")", ")", "\n", "}", "\n", "if", "config", ".", "UntilDate", "!=", "0", "{", "v", ".", "Add", "(", "\"until_date\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "UntilDate", ",", "10", ")", ")", "\n", "}", "\n", "bot", ".", "debugLog", "(", "\"restrictChatMember\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"restrictChatMember\"", ",", "v", ")", "\n", "}" ]
// RestrictChatMember to restrict a user in a supergroup. The bot must be an //administrator in the supergroup for this to work and must have the //appropriate admin rights. Pass True for all boolean parameters to lift //restrictions from a user. Returns True on success.
[ "RestrictChatMember", "to", "restrict", "a", "user", "in", "a", "supergroup", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "supergroup", "for", "this", "to", "work", "and", "must", "have", "the", "appropriate", "admin", "rights", ".", "Pass", "True", "for", "all", "boolean", "parameters", "to", "lift", "restrictions", "from", "a", "user", ".", "Returns", "True", "on", "success", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L738-L769
train
go-telegram-bot-api/telegram-bot-api
bot.go
PromoteChatMember
func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.CanChangeInfo != nil { v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo)) } if config.CanPostMessages != nil { v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages)) } if config.CanEditMessages != nil { v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages)) } if config.CanDeleteMessages != nil { v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages)) } if config.CanInviteUsers != nil { v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers)) } if config.CanRestrictMembers != nil { v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers)) } if config.CanPinMessages != nil { v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages)) } if config.CanPromoteMembers != nil { v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers)) } bot.debugLog("promoteChatMember", v, nil) return bot.MakeRequest("promoteChatMember", v) }
go
func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.CanChangeInfo != nil { v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo)) } if config.CanPostMessages != nil { v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages)) } if config.CanEditMessages != nil { v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages)) } if config.CanDeleteMessages != nil { v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages)) } if config.CanInviteUsers != nil { v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers)) } if config.CanRestrictMembers != nil { v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers)) } if config.CanPinMessages != nil { v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages)) } if config.CanPromoteMembers != nil { v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers)) } bot.debugLog("promoteChatMember", v, nil) return bot.MakeRequest("promoteChatMember", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "PromoteChatMember", "(", "config", "PromoteChatMemberConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "else", "if", "config", ".", "ChannelUsername", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "ChannelUsername", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"user_id\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n", "if", "config", ".", "CanChangeInfo", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_change_info\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanChangeInfo", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanPostMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_post_messages\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanPostMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanEditMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_edit_messages\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanEditMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanDeleteMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_delete_messages\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanDeleteMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanInviteUsers", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_invite_users\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanInviteUsers", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanRestrictMembers", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_restrict_members\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanRestrictMembers", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanPinMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_pin_messages\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanPinMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanPromoteMembers", "!=", "nil", "{", "v", ".", "Add", "(", "\"can_promote_members\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanPromoteMembers", ")", ")", "\n", "}", "\n", "bot", ".", "debugLog", "(", "\"promoteChatMember\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"promoteChatMember\"", ",", "v", ")", "\n", "}" ]
// PromoteChatMember add admin rights to user
[ "PromoteChatMember", "add", "admin", "rights", "to", "user" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L772-L812
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetGameHighScores
func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) { v, _ := config.values() resp, err := bot.MakeRequest(config.method(), v) if err != nil { return []GameHighScore{}, err } var highScores []GameHighScore err = json.Unmarshal(resp.Result, &highScores) return highScores, err }
go
func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) { v, _ := config.values() resp, err := bot.MakeRequest(config.method(), v) if err != nil { return []GameHighScore{}, err } var highScores []GameHighScore err = json.Unmarshal(resp.Result, &highScores) return highScores, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetGameHighScores", "(", "config", "GetGameHighScoresConfig", ")", "(", "[", "]", "GameHighScore", ",", "error", ")", "{", "v", ",", "_", ":=", "config", ".", "values", "(", ")", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "GameHighScore", "{", "}", ",", "err", "\n", "}", "\n", "var", "highScores", "[", "]", "GameHighScore", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "highScores", ")", "\n", "return", "highScores", ",", "err", "\n", "}" ]
// GetGameHighScores allows you to get the high scores for a game.
[ "GetGameHighScores", "allows", "you", "to", "get", "the", "high", "scores", "for", "a", "game", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L815-L827
train
go-telegram-bot-api/telegram-bot-api
bot.go
AnswerShippingQuery
func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) { v := url.Values{} v.Add("shipping_query_id", config.ShippingQueryID) v.Add("ok", strconv.FormatBool(config.OK)) if config.OK == true { data, err := json.Marshal(config.ShippingOptions) if err != nil { return APIResponse{}, err } v.Add("shipping_options", string(data)) } else { v.Add("error_message", config.ErrorMessage) } bot.debugLog("answerShippingQuery", v, nil) return bot.MakeRequest("answerShippingQuery", v) }
go
func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) { v := url.Values{} v.Add("shipping_query_id", config.ShippingQueryID) v.Add("ok", strconv.FormatBool(config.OK)) if config.OK == true { data, err := json.Marshal(config.ShippingOptions) if err != nil { return APIResponse{}, err } v.Add("shipping_options", string(data)) } else { v.Add("error_message", config.ErrorMessage) } bot.debugLog("answerShippingQuery", v, nil) return bot.MakeRequest("answerShippingQuery", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "AnswerShippingQuery", "(", "config", "ShippingConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "v", ".", "Add", "(", "\"shipping_query_id\"", ",", "config", ".", "ShippingQueryID", ")", "\n", "v", ".", "Add", "(", "\"ok\"", ",", "strconv", ".", "FormatBool", "(", "config", ".", "OK", ")", ")", "\n", "if", "config", ".", "OK", "==", "true", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "config", ".", "ShippingOptions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"shipping_options\"", ",", "string", "(", "data", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"error_message\"", ",", "config", ".", "ErrorMessage", ")", "\n", "}", "\n", "bot", ".", "debugLog", "(", "\"answerShippingQuery\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"answerShippingQuery\"", ",", "v", ")", "\n", "}" ]
// AnswerShippingQuery allows you to reply to Update with shipping_query parameter.
[ "AnswerShippingQuery", "allows", "you", "to", "reply", "to", "Update", "with", "shipping_query", "parameter", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L830-L848
train
go-telegram-bot-api/telegram-bot-api
bot.go
AnswerPreCheckoutQuery
func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) { v := url.Values{} v.Add("pre_checkout_query_id", config.PreCheckoutQueryID) v.Add("ok", strconv.FormatBool(config.OK)) if config.OK != true { v.Add("error", config.ErrorMessage) } bot.debugLog("answerPreCheckoutQuery", v, nil) return bot.MakeRequest("answerPreCheckoutQuery", v) }
go
func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) { v := url.Values{} v.Add("pre_checkout_query_id", config.PreCheckoutQueryID) v.Add("ok", strconv.FormatBool(config.OK)) if config.OK != true { v.Add("error", config.ErrorMessage) } bot.debugLog("answerPreCheckoutQuery", v, nil) return bot.MakeRequest("answerPreCheckoutQuery", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "AnswerPreCheckoutQuery", "(", "config", "PreCheckoutConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "v", ".", "Add", "(", "\"pre_checkout_query_id\"", ",", "config", ".", "PreCheckoutQueryID", ")", "\n", "v", ".", "Add", "(", "\"ok\"", ",", "strconv", ".", "FormatBool", "(", "config", ".", "OK", ")", ")", "\n", "if", "config", ".", "OK", "!=", "true", "{", "v", ".", "Add", "(", "\"error\"", ",", "config", ".", "ErrorMessage", ")", "\n", "}", "\n", "bot", ".", "debugLog", "(", "\"answerPreCheckoutQuery\"", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "\"answerPreCheckoutQuery\"", ",", "v", ")", "\n", "}" ]
// AnswerPreCheckoutQuery allows you to reply to Update with pre_checkout_query.
[ "AnswerPreCheckoutQuery", "allows", "you", "to", "reply", "to", "Update", "with", "pre_checkout_query", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L851-L863
train
go-telegram-bot-api/telegram-bot-api
bot.go
DeleteMessage
func (bot *BotAPI) DeleteMessage(config DeleteMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) DeleteMessage(config DeleteMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "DeleteMessage", "(", "config", "DeleteMessageConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// DeleteMessage deletes a message in a chat
[ "DeleteMessage", "deletes", "a", "message", "in", "a", "chat" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L866-L875
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetInviteLink
func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("exportChatInviteLink", v) if err != nil { return "", err } var inviteLink string err = json.Unmarshal(resp.Result, &inviteLink) return inviteLink, err }
go
func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("exportChatInviteLink", v) if err != nil { return "", err } var inviteLink string err = json.Unmarshal(resp.Result, &inviteLink) return inviteLink, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetInviteLink", "(", "config", "ChatConfig", ")", "(", "string", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "config", ".", "SuperGroupUsername", "==", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"exportChatInviteLink\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "var", "inviteLink", "string", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "inviteLink", ")", "\n", "return", "inviteLink", ",", "err", "\n", "}" ]
// GetInviteLink get InviteLink for a chat
[ "GetInviteLink", "get", "InviteLink", "for", "a", "chat" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L878-L896
train
go-telegram-bot-api/telegram-bot-api
bot.go
PinChatMessage
func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "PinChatMessage", "(", "config", "PinChatMessageConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// PinChatMessage pin message in supergroup
[ "PinChatMessage", "pin", "message", "in", "supergroup" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L899-L908
train
go-telegram-bot-api/telegram-bot-api
bot.go
UnpinChatMessage
func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "UnpinChatMessage", "(", "config", "UnpinChatMessageConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// UnpinChatMessage unpin message in supergroup
[ "UnpinChatMessage", "unpin", "message", "in", "supergroup" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L911-L920
train
go-telegram-bot-api/telegram-bot-api
bot.go
SetChatTitle
func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "SetChatTitle", "(", "config", "SetChatTitleConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// SetChatTitle change title of chat.
[ "SetChatTitle", "change", "title", "of", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L923-L932
train
go-telegram-bot-api/telegram-bot-api
bot.go
SetChatDescription
func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "SetChatDescription", "(", "config", "SetChatDescriptionConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// SetChatDescription change description of chat.
[ "SetChatDescription", "change", "description", "of", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L935-L944
train
go-telegram-bot-api/telegram-bot-api
bot.go
SetChatPhoto
func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) { params, err := config.params() if err != nil { return APIResponse{}, err } file := config.getFile() return bot.UploadFile(config.method(), params, config.name(), file) }
go
func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) { params, err := config.params() if err != nil { return APIResponse{}, err } file := config.getFile() return bot.UploadFile(config.method(), params, config.name(), file) }
[ "func", "(", "bot", "*", "BotAPI", ")", "SetChatPhoto", "(", "config", "SetChatPhotoConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "params", ",", "err", ":=", "config", ".", "params", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "file", ":=", "config", ".", "getFile", "(", ")", "\n", "return", "bot", ".", "UploadFile", "(", "config", ".", "method", "(", ")", ",", "params", ",", "config", ".", "name", "(", ")", ",", "file", ")", "\n", "}" ]
// SetChatPhoto change photo of chat.
[ "SetChatPhoto", "change", "photo", "of", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L947-L956
train
go-telegram-bot-api/telegram-bot-api
bot.go
DeleteChatPhoto
func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "DeleteChatPhoto", "(", "config", "DeleteChatPhotoConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// DeleteChatPhoto delete photo of chat.
[ "DeleteChatPhoto", "delete", "photo", "of", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L959-L968
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (chat *BaseChat) values() (url.Values, error) { v := url.Values{} if chat.ChannelUsername != "" { v.Add("chat_id", chat.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(chat.ChatID, 10)) } if chat.ReplyToMessageID != 0 { v.Add("reply_to_message_id", strconv.Itoa(chat.ReplyToMessageID)) } if chat.ReplyMarkup != nil { data, err := json.Marshal(chat.ReplyMarkup) if err != nil { return v, err } v.Add("reply_markup", string(data)) } v.Add("disable_notification", strconv.FormatBool(chat.DisableNotification)) return v, nil }
go
func (chat *BaseChat) values() (url.Values, error) { v := url.Values{} if chat.ChannelUsername != "" { v.Add("chat_id", chat.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(chat.ChatID, 10)) } if chat.ReplyToMessageID != 0 { v.Add("reply_to_message_id", strconv.Itoa(chat.ReplyToMessageID)) } if chat.ReplyMarkup != nil { data, err := json.Marshal(chat.ReplyMarkup) if err != nil { return v, err } v.Add("reply_markup", string(data)) } v.Add("disable_notification", strconv.FormatBool(chat.DisableNotification)) return v, nil }
[ "func", "(", "chat", "*", "BaseChat", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "chat", ".", "ChannelUsername", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "chat", ".", "ChannelUsername", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"chat_id\"", ",", "strconv", ".", "FormatInt", "(", "chat", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "\n", "if", "chat", ".", "ReplyToMessageID", "!=", "0", "{", "v", ".", "Add", "(", "\"reply_to_message_id\"", ",", "strconv", ".", "Itoa", "(", "chat", ".", "ReplyToMessageID", ")", ")", "\n", "}", "\n", "if", "chat", ".", "ReplyMarkup", "!=", "nil", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "chat", ".", "ReplyMarkup", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"reply_markup\"", ",", "string", "(", "data", ")", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"disable_notification\"", ",", "strconv", ".", "FormatBool", "(", "chat", ".", "DisableNotification", ")", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns url.Values representation of BaseChat
[ "values", "returns", "url", ".", "Values", "representation", "of", "BaseChat" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L75-L99
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config MessageConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("text", config.Text) v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview)) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } return v, nil }
go
func (config MessageConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("text", config.Text) v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview)) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } return v, nil }
[ "func", "(", "config", "MessageConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"text\"", ",", "config", ".", "Text", ")", "\n", "v", ".", "Add", "(", "\"disable_web_page_preview\"", ",", "strconv", ".", "FormatBool", "(", "config", ".", "DisableWebPagePreview", ")", ")", "\n", "if", "config", ".", "ParseMode", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"parse_mode\"", ",", "config", ".", "ParseMode", ")", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of MessageConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "MessageConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L200-L212
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config ForwardConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("from_chat_id", strconv.FormatInt(config.FromChatID, 10)) v.Add("message_id", strconv.Itoa(config.MessageID)) return v, nil }
go
func (config ForwardConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("from_chat_id", strconv.FormatInt(config.FromChatID, 10)) v.Add("message_id", strconv.Itoa(config.MessageID)) return v, nil }
[ "func", "(", "config", "ForwardConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"from_chat_id\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "FromChatID", ",", "10", ")", ")", "\n", "v", ".", "Add", "(", "\"message_id\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "MessageID", ")", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of ForwardConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "ForwardConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L228-L236
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config DocumentConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Caption != "" { v.Add("caption", config.Caption) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } } return v, nil }
go
func (config DocumentConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Caption != "" { v.Add("caption", config.Caption) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } } return v, nil }
[ "func", "(", "config", "DocumentConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "config", ".", "name", "(", ")", ",", "config", ".", "FileID", ")", "\n", "if", "config", ".", "Caption", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"caption\"", ",", "config", ".", "Caption", ")", "\n", "if", "config", ".", "ParseMode", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"parse_mode\"", ",", "config", ".", "ParseMode", ")", "\n", "}", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of DocumentConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "DocumentConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L372-L387
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config StickerConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) return v, nil }
go
func (config StickerConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) return v, nil }
[ "func", "(", "config", "StickerConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "config", ".", "name", "(", ")", ",", "config", ".", "FileID", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of StickerConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "StickerConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L419-L428
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config VideoConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Duration != 0 { v.Add("duration", strconv.Itoa(config.Duration)) } if config.Caption != "" { v.Add("caption", config.Caption) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } } return v, nil }
go
func (config VideoConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Duration != 0 { v.Add("duration", strconv.Itoa(config.Duration)) } if config.Caption != "" { v.Add("caption", config.Caption) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } } return v, nil }
[ "func", "(", "config", "VideoConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "config", ".", "name", "(", ")", ",", "config", ".", "FileID", ")", "\n", "if", "config", ".", "Duration", "!=", "0", "{", "v", ".", "Add", "(", "\"duration\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Duration", ")", ")", "\n", "}", "\n", "if", "config", ".", "Caption", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"caption\"", ",", "config", ".", "Caption", ")", "\n", "if", "config", ".", "ParseMode", "!=", "\"\"", "{", "v", ".", "Add", "(", "\"parse_mode\"", ",", "config", ".", "ParseMode", ")", "\n", "}", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of VideoConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "VideoConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L456-L474
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config VideoNoteConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Duration != 0 { v.Add("duration", strconv.Itoa(config.Duration)) } // Telegram API seems to have a bug, if no length is provided or it is 0, it will send an error response if config.Length != 0 { v.Add("length", strconv.Itoa(config.Length)) } return v, nil }
go
func (config VideoNoteConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Duration != 0 { v.Add("duration", strconv.Itoa(config.Duration)) } // Telegram API seems to have a bug, if no length is provided or it is 0, it will send an error response if config.Length != 0 { v.Add("length", strconv.Itoa(config.Length)) } return v, nil }
[ "func", "(", "config", "VideoNoteConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "config", ".", "name", "(", ")", ",", "config", ".", "FileID", ")", "\n", "if", "config", ".", "Duration", "!=", "0", "{", "v", ".", "Add", "(", "\"duration\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Duration", ")", ")", "\n", "}", "\n", "if", "config", ".", "Length", "!=", "0", "{", "v", ".", "Add", "(", "\"length\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Length", ")", ")", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of VideoNoteConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "VideoNoteConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L561-L578
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config LocationConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64)) v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64)) return v, nil }
go
func (config LocationConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64)) v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64)) return v, nil }
[ "func", "(", "config", "LocationConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"latitude\"", ",", "strconv", ".", "FormatFloat", "(", "config", ".", "Latitude", ",", "'f'", ",", "6", ",", "64", ")", ")", "\n", "v", ".", "Add", "(", "\"longitude\"", ",", "strconv", ".", "FormatFloat", "(", "config", ".", "Longitude", ",", "'f'", ",", "6", ",", "64", ")", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of LocationConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "LocationConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L694-L704
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config ChatActionConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("action", config.Action) return v, nil }
go
func (config ChatActionConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("action", config.Action) return v, nil }
[ "func", "(", "config", "ChatActionConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"action\"", ",", "config", ".", "Action", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of ChatActionConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "ChatActionConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L862-L869
train
go-telegram-bot-api/telegram-bot-api
log.go
SetLogger
func SetLogger(logger BotLogger) error { if logger == nil { return errors.New("logger is nil") } log = logger return nil }
go
func SetLogger(logger BotLogger) error { if logger == nil { return errors.New("logger is nil") } log = logger return nil }
[ "func", "SetLogger", "(", "logger", "BotLogger", ")", "error", "{", "if", "logger", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"logger is nil\"", ")", "\n", "}", "\n", "log", "=", "logger", "\n", "return", "nil", "\n", "}" ]
// SetLogger specifies the logger that the package should use.
[ "SetLogger", "specifies", "the", "logger", "that", "the", "package", "should", "use", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/log.go#L21-L27
train
nsf/termbox-go
termbox_windows.go
prepare_diff_messages
func prepare_diff_messages() { // clear buffers diffbuf = diffbuf[:0] charbuf = charbuf[:0] var diff diff_msg gbeg := 0 for y := 0; y < front_buffer.height; y++ { same := true line_offset := y * front_buffer.width for x := 0; x < front_buffer.width; x++ { cell_offset := line_offset + x back := &back_buffer.cells[cell_offset] front := &front_buffer.cells[cell_offset] if *back != *front { same = false break } } if same && diff.lines > 0 { diffbuf = append(diffbuf, diff) diff = diff_msg{} } if !same { beg := len(charbuf) end := beg + append_diff_line(y) if diff.lines == 0 { diff.pos = short(y) gbeg = beg } diff.lines++ diff.chars = charbuf[gbeg:end] } } if diff.lines > 0 { diffbuf = append(diffbuf, diff) diff = diff_msg{} } }
go
func prepare_diff_messages() { // clear buffers diffbuf = diffbuf[:0] charbuf = charbuf[:0] var diff diff_msg gbeg := 0 for y := 0; y < front_buffer.height; y++ { same := true line_offset := y * front_buffer.width for x := 0; x < front_buffer.width; x++ { cell_offset := line_offset + x back := &back_buffer.cells[cell_offset] front := &front_buffer.cells[cell_offset] if *back != *front { same = false break } } if same && diff.lines > 0 { diffbuf = append(diffbuf, diff) diff = diff_msg{} } if !same { beg := len(charbuf) end := beg + append_diff_line(y) if diff.lines == 0 { diff.pos = short(y) gbeg = beg } diff.lines++ diff.chars = charbuf[gbeg:end] } } if diff.lines > 0 { diffbuf = append(diffbuf, diff) diff = diff_msg{} } }
[ "func", "prepare_diff_messages", "(", ")", "{", "diffbuf", "=", "diffbuf", "[", ":", "0", "]", "\n", "charbuf", "=", "charbuf", "[", ":", "0", "]", "\n", "var", "diff", "diff_msg", "\n", "gbeg", ":=", "0", "\n", "for", "y", ":=", "0", ";", "y", "<", "front_buffer", ".", "height", ";", "y", "++", "{", "same", ":=", "true", "\n", "line_offset", ":=", "y", "*", "front_buffer", ".", "width", "\n", "for", "x", ":=", "0", ";", "x", "<", "front_buffer", ".", "width", ";", "x", "++", "{", "cell_offset", ":=", "line_offset", "+", "x", "\n", "back", ":=", "&", "back_buffer", ".", "cells", "[", "cell_offset", "]", "\n", "front", ":=", "&", "front_buffer", ".", "cells", "[", "cell_offset", "]", "\n", "if", "*", "back", "!=", "*", "front", "{", "same", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "same", "&&", "diff", ".", "lines", ">", "0", "{", "diffbuf", "=", "append", "(", "diffbuf", ",", "diff", ")", "\n", "diff", "=", "diff_msg", "{", "}", "\n", "}", "\n", "if", "!", "same", "{", "beg", ":=", "len", "(", "charbuf", ")", "\n", "end", ":=", "beg", "+", "append_diff_line", "(", "y", ")", "\n", "if", "diff", ".", "lines", "==", "0", "{", "diff", ".", "pos", "=", "short", "(", "y", ")", "\n", "gbeg", "=", "beg", "\n", "}", "\n", "diff", ".", "lines", "++", "\n", "diff", ".", "chars", "=", "charbuf", "[", "gbeg", ":", "end", "]", "\n", "}", "\n", "}", "\n", "if", "diff", ".", "lines", ">", "0", "{", "diffbuf", "=", "append", "(", "diffbuf", ",", "diff", ")", "\n", "diff", "=", "diff_msg", "{", "}", "\n", "}", "\n", "}" ]
// compares 'back_buffer' with 'front_buffer' and prepares all changes in the form of // 'diff_msg's in the 'diff_buf'
[ "compares", "back_buffer", "with", "front_buffer", "and", "prepares", "all", "changes", "in", "the", "form", "of", "diff_msg", "s", "in", "the", "diff_buf" ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/termbox_windows.go#L577-L615
train
nsf/termbox-go
api_windows.go
SetCell
func SetCell(x, y int, ch rune, fg, bg Attribute) { if x < 0 || x >= back_buffer.width { return } if y < 0 || y >= back_buffer.height { return } back_buffer.cells[y*back_buffer.width+x] = Cell{ch, fg, bg} }
go
func SetCell(x, y int, ch rune, fg, bg Attribute) { if x < 0 || x >= back_buffer.width { return } if y < 0 || y >= back_buffer.height { return } back_buffer.cells[y*back_buffer.width+x] = Cell{ch, fg, bg} }
[ "func", "SetCell", "(", "x", ",", "y", "int", ",", "ch", "rune", ",", "fg", ",", "bg", "Attribute", ")", "{", "if", "x", "<", "0", "||", "x", ">=", "back_buffer", ".", "width", "{", "return", "\n", "}", "\n", "if", "y", "<", "0", "||", "y", ">=", "back_buffer", ".", "height", "{", "return", "\n", "}", "\n", "back_buffer", ".", "cells", "[", "y", "*", "back_buffer", ".", "width", "+", "x", "]", "=", "Cell", "{", "ch", ",", "fg", ",", "bg", "}", "\n", "}" ]
// Changes cell's parameters in the internal back buffer at the specified // position.
[ "Changes", "cell", "s", "parameters", "in", "the", "internal", "back", "buffer", "at", "the", "specified", "position", "." ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/api_windows.go#L154-L163
train
nsf/termbox-go
_demos/editbox.go
Draw
func (eb *EditBox) Draw(x, y, w, h int) { eb.AdjustVOffset(w) const coldef = termbox.ColorDefault fill(x, y, w, h, termbox.Cell{Ch: ' '}) t := eb.text lx := 0 tabstop := 0 for { rx := lx - eb.line_voffset if len(t) == 0 { break } if lx == tabstop { tabstop += tabstop_length } if rx >= w { termbox.SetCell(x+w-1, y, 'β†’', coldef, coldef) break } r, size := utf8.DecodeRune(t) if r == '\t' { for ; lx < tabstop; lx++ { rx = lx - eb.line_voffset if rx >= w { goto next } if rx >= 0 { termbox.SetCell(x+rx, y, ' ', coldef, coldef) } } } else { if rx >= 0 { termbox.SetCell(x+rx, y, r, coldef, coldef) } lx += runewidth.RuneWidth(r) } next: t = t[size:] } if eb.line_voffset != 0 { termbox.SetCell(x, y, '←', coldef, coldef) } }
go
func (eb *EditBox) Draw(x, y, w, h int) { eb.AdjustVOffset(w) const coldef = termbox.ColorDefault fill(x, y, w, h, termbox.Cell{Ch: ' '}) t := eb.text lx := 0 tabstop := 0 for { rx := lx - eb.line_voffset if len(t) == 0 { break } if lx == tabstop { tabstop += tabstop_length } if rx >= w { termbox.SetCell(x+w-1, y, 'β†’', coldef, coldef) break } r, size := utf8.DecodeRune(t) if r == '\t' { for ; lx < tabstop; lx++ { rx = lx - eb.line_voffset if rx >= w { goto next } if rx >= 0 { termbox.SetCell(x+rx, y, ' ', coldef, coldef) } } } else { if rx >= 0 { termbox.SetCell(x+rx, y, r, coldef, coldef) } lx += runewidth.RuneWidth(r) } next: t = t[size:] } if eb.line_voffset != 0 { termbox.SetCell(x, y, '←', coldef, coldef) } }
[ "func", "(", "eb", "*", "EditBox", ")", "Draw", "(", "x", ",", "y", ",", "w", ",", "h", "int", ")", "{", "eb", ".", "AdjustVOffset", "(", "w", ")", "\n", "const", "coldef", "=", "termbox", ".", "ColorDefault", "\n", "fill", "(", "x", ",", "y", ",", "w", ",", "h", ",", "termbox", ".", "Cell", "{", "Ch", ":", "' '", "}", ")", "\n", "t", ":=", "eb", ".", "text", "\n", "lx", ":=", "0", "\n", "tabstop", ":=", "0", "\n", "for", "{", "rx", ":=", "lx", "-", "eb", ".", "line_voffset", "\n", "if", "len", "(", "t", ")", "==", "0", "{", "break", "\n", "}", "\n", "if", "lx", "==", "tabstop", "{", "tabstop", "+=", "tabstop_length", "\n", "}", "\n", "if", "rx", ">=", "w", "{", "termbox", ".", "SetCell", "(", "x", "+", "w", "-", "1", ",", "y", ",", "'β†’',", ",", "coldef", ",", "coldef", ")", "\n", "break", "\n", "}", "\n", "r", ",", "size", ":=", "utf8", ".", "DecodeRune", "(", "t", ")", "\n", "if", "r", "==", "'\\t'", "{", "for", ";", "lx", "<", "tabstop", ";", "lx", "++", "{", "rx", "=", "lx", "-", "eb", ".", "line_voffset", "\n", "if", "rx", ">=", "w", "{", "goto", "next", "\n", "}", "\n", "if", "rx", ">=", "0", "{", "termbox", ".", "SetCell", "(", "x", "+", "rx", ",", "y", ",", "' '", ",", "coldef", ",", "coldef", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "if", "rx", ">=", "0", "{", "termbox", ".", "SetCell", "(", "x", "+", "rx", ",", "y", ",", "r", ",", "coldef", ",", "coldef", ")", "\n", "}", "\n", "lx", "+=", "runewidth", ".", "RuneWidth", "(", "r", ")", "\n", "}", "\n", "next", ":", "t", "=", "t", "[", "size", ":", "]", "\n", "}", "\n", "if", "eb", ".", "line_voffset", "!=", "0", "{", "termbox", ".", "SetCell", "(", "x", ",", "y", ",", "'←', ", "c", "ldef, ", "c", "ldef)", ")", "\n", "}", "\n", "}" ]
// Draws the EditBox in the given location, 'h' is not used at the moment
[ "Draws", "the", "EditBox", "in", "the", "given", "location", "h", "is", "not", "used", "at", "the", "moment" ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/_demos/editbox.go#L79-L129
train
nsf/termbox-go
_demos/editbox.go
AdjustVOffset
func (eb *EditBox) AdjustVOffset(width int) { ht := preferred_horizontal_threshold max_h_threshold := (width - 1) / 2 if ht > max_h_threshold { ht = max_h_threshold } threshold := width - 1 if eb.line_voffset != 0 { threshold = width - ht } if eb.cursor_voffset-eb.line_voffset >= threshold { eb.line_voffset = eb.cursor_voffset + (ht - width + 1) } if eb.line_voffset != 0 && eb.cursor_voffset-eb.line_voffset < ht { eb.line_voffset = eb.cursor_voffset - ht if eb.line_voffset < 0 { eb.line_voffset = 0 } } }
go
func (eb *EditBox) AdjustVOffset(width int) { ht := preferred_horizontal_threshold max_h_threshold := (width - 1) / 2 if ht > max_h_threshold { ht = max_h_threshold } threshold := width - 1 if eb.line_voffset != 0 { threshold = width - ht } if eb.cursor_voffset-eb.line_voffset >= threshold { eb.line_voffset = eb.cursor_voffset + (ht - width + 1) } if eb.line_voffset != 0 && eb.cursor_voffset-eb.line_voffset < ht { eb.line_voffset = eb.cursor_voffset - ht if eb.line_voffset < 0 { eb.line_voffset = 0 } } }
[ "func", "(", "eb", "*", "EditBox", ")", "AdjustVOffset", "(", "width", "int", ")", "{", "ht", ":=", "preferred_horizontal_threshold", "\n", "max_h_threshold", ":=", "(", "width", "-", "1", ")", "/", "2", "\n", "if", "ht", ">", "max_h_threshold", "{", "ht", "=", "max_h_threshold", "\n", "}", "\n", "threshold", ":=", "width", "-", "1", "\n", "if", "eb", ".", "line_voffset", "!=", "0", "{", "threshold", "=", "width", "-", "ht", "\n", "}", "\n", "if", "eb", ".", "cursor_voffset", "-", "eb", ".", "line_voffset", ">=", "threshold", "{", "eb", ".", "line_voffset", "=", "eb", ".", "cursor_voffset", "+", "(", "ht", "-", "width", "+", "1", ")", "\n", "}", "\n", "if", "eb", ".", "line_voffset", "!=", "0", "&&", "eb", ".", "cursor_voffset", "-", "eb", ".", "line_voffset", "<", "ht", "{", "eb", ".", "line_voffset", "=", "eb", ".", "cursor_voffset", "-", "ht", "\n", "if", "eb", ".", "line_voffset", "<", "0", "{", "eb", ".", "line_voffset", "=", "0", "\n", "}", "\n", "}", "\n", "}" ]
// Adjusts line visual offset to a proper value depending on width
[ "Adjusts", "line", "visual", "offset", "to", "a", "proper", "value", "depending", "on", "width" ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/_demos/editbox.go#L132-L153
train
nsf/termbox-go
api.go
PollEvent
func PollEvent() Event { // Constant governing macOS specific behavior. See https://github.com/nsf/termbox-go/issues/132 // This is an arbitrary delay which hopefully will be enough time for any lagging // partial escape sequences to come through. const esc_wait_delay = 100 * time.Millisecond var event Event var esc_wait_timer *time.Timer var esc_timeout <-chan time.Time // try to extract event from input buffer, return on success event.Type = EventKey status := extract_event(inbuf, &event, true) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } else if status == esc_wait { esc_wait_timer = time.NewTimer(esc_wait_delay) esc_timeout = esc_wait_timer.C } for { select { case ev := <-input_comm: if esc_wait_timer != nil { if !esc_wait_timer.Stop() { <-esc_wait_timer.C } esc_wait_timer = nil } if ev.err != nil { return Event{Type: EventError, Err: ev.err} } inbuf = append(inbuf, ev.data...) input_comm <- ev status := extract_event(inbuf, &event, true) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } else if status == esc_wait { esc_wait_timer = time.NewTimer(esc_wait_delay) esc_timeout = esc_wait_timer.C } case <-esc_timeout: esc_wait_timer = nil status := extract_event(inbuf, &event, false) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } case <-interrupt_comm: event.Type = EventInterrupt return event case <-sigwinch: event.Type = EventResize event.Width, event.Height = get_term_size(out.Fd()) return event } } }
go
func PollEvent() Event { // Constant governing macOS specific behavior. See https://github.com/nsf/termbox-go/issues/132 // This is an arbitrary delay which hopefully will be enough time for any lagging // partial escape sequences to come through. const esc_wait_delay = 100 * time.Millisecond var event Event var esc_wait_timer *time.Timer var esc_timeout <-chan time.Time // try to extract event from input buffer, return on success event.Type = EventKey status := extract_event(inbuf, &event, true) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } else if status == esc_wait { esc_wait_timer = time.NewTimer(esc_wait_delay) esc_timeout = esc_wait_timer.C } for { select { case ev := <-input_comm: if esc_wait_timer != nil { if !esc_wait_timer.Stop() { <-esc_wait_timer.C } esc_wait_timer = nil } if ev.err != nil { return Event{Type: EventError, Err: ev.err} } inbuf = append(inbuf, ev.data...) input_comm <- ev status := extract_event(inbuf, &event, true) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } else if status == esc_wait { esc_wait_timer = time.NewTimer(esc_wait_delay) esc_timeout = esc_wait_timer.C } case <-esc_timeout: esc_wait_timer = nil status := extract_event(inbuf, &event, false) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } case <-interrupt_comm: event.Type = EventInterrupt return event case <-sigwinch: event.Type = EventResize event.Width, event.Height = get_term_size(out.Fd()) return event } } }
[ "func", "PollEvent", "(", ")", "Event", "{", "const", "esc_wait_delay", "=", "100", "*", "time", ".", "Millisecond", "\n", "var", "event", "Event", "\n", "var", "esc_wait_timer", "*", "time", ".", "Timer", "\n", "var", "esc_timeout", "<-", "chan", "time", ".", "Time", "\n", "event", ".", "Type", "=", "EventKey", "\n", "status", ":=", "extract_event", "(", "inbuf", ",", "&", "event", ",", "true", ")", "\n", "if", "event", ".", "N", "!=", "0", "{", "copy", "(", "inbuf", ",", "inbuf", "[", "event", ".", "N", ":", "]", ")", "\n", "inbuf", "=", "inbuf", "[", ":", "len", "(", "inbuf", ")", "-", "event", ".", "N", "]", "\n", "}", "\n", "if", "status", "==", "event_extracted", "{", "return", "event", "\n", "}", "else", "if", "status", "==", "esc_wait", "{", "esc_wait_timer", "=", "time", ".", "NewTimer", "(", "esc_wait_delay", ")", "\n", "esc_timeout", "=", "esc_wait_timer", ".", "C", "\n", "}", "\n", "for", "{", "select", "{", "case", "ev", ":=", "<-", "input_comm", ":", "if", "esc_wait_timer", "!=", "nil", "{", "if", "!", "esc_wait_timer", ".", "Stop", "(", ")", "{", "<-", "esc_wait_timer", ".", "C", "\n", "}", "\n", "esc_wait_timer", "=", "nil", "\n", "}", "\n", "if", "ev", ".", "err", "!=", "nil", "{", "return", "Event", "{", "Type", ":", "EventError", ",", "Err", ":", "ev", ".", "err", "}", "\n", "}", "\n", "inbuf", "=", "append", "(", "inbuf", ",", "ev", ".", "data", "...", ")", "\n", "input_comm", "<-", "ev", "\n", "status", ":=", "extract_event", "(", "inbuf", ",", "&", "event", ",", "true", ")", "\n", "if", "event", ".", "N", "!=", "0", "{", "copy", "(", "inbuf", ",", "inbuf", "[", "event", ".", "N", ":", "]", ")", "\n", "inbuf", "=", "inbuf", "[", ":", "len", "(", "inbuf", ")", "-", "event", ".", "N", "]", "\n", "}", "\n", "if", "status", "==", "event_extracted", "{", "return", "event", "\n", "}", "else", "if", "status", "==", "esc_wait", "{", "esc_wait_timer", "=", "time", ".", "NewTimer", "(", "esc_wait_delay", ")", "\n", "esc_timeout", "=", "esc_wait_timer", ".", "C", "\n", "}", "\n", "case", "<-", "esc_timeout", ":", "esc_wait_timer", "=", "nil", "\n", "status", ":=", "extract_event", "(", "inbuf", ",", "&", "event", ",", "false", ")", "\n", "if", "event", ".", "N", "!=", "0", "{", "copy", "(", "inbuf", ",", "inbuf", "[", "event", ".", "N", ":", "]", ")", "\n", "inbuf", "=", "inbuf", "[", ":", "len", "(", "inbuf", ")", "-", "event", ".", "N", "]", "\n", "}", "\n", "if", "status", "==", "event_extracted", "{", "return", "event", "\n", "}", "\n", "case", "<-", "interrupt_comm", ":", "event", ".", "Type", "=", "EventInterrupt", "\n", "return", "event", "\n", "case", "<-", "sigwinch", ":", "event", ".", "Type", "=", "EventResize", "\n", "event", ".", "Width", ",", "event", ".", "Height", "=", "get_term_size", "(", "out", ".", "Fd", "(", ")", ")", "\n", "return", "event", "\n", "}", "\n", "}", "\n", "}" ]
// Wait for an event and return it. This is a blocking function call.
[ "Wait", "for", "an", "event", "and", "return", "it", ".", "This", "is", "a", "blocking", "function", "call", "." ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/api.go#L314-L386
train
nsf/termbox-go
api.go
Clear
func Clear(fg, bg Attribute) error { foreground, background = fg, bg err := update_size_maybe() back_buffer.clear() return err }
go
func Clear(fg, bg Attribute) error { foreground, background = fg, bg err := update_size_maybe() back_buffer.clear() return err }
[ "func", "Clear", "(", "fg", ",", "bg", "Attribute", ")", "error", "{", "foreground", ",", "background", "=", "fg", ",", "bg", "\n", "err", ":=", "update_size_maybe", "(", ")", "\n", "back_buffer", ".", "clear", "(", ")", "\n", "return", "err", "\n", "}" ]
// Clears the internal back buffer.
[ "Clears", "the", "internal", "back", "buffer", "." ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/api.go#L397-L402
train
nsf/termbox-go
api.go
Sync
func Sync() error { front_buffer.clear() err := send_clear() if err != nil { return err } return Flush() }
go
func Sync() error { front_buffer.clear() err := send_clear() if err != nil { return err } return Flush() }
[ "func", "Sync", "(", ")", "error", "{", "front_buffer", ".", "clear", "(", ")", "\n", "err", ":=", "send_clear", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "Flush", "(", ")", "\n", "}" ]
// Sync comes handy when something causes desync between termbox's understanding // of a terminal buffer and the reality. Such as a third party process. Sync // forces a complete resync between the termbox and a terminal, it may not be // visually pretty though.
[ "Sync", "comes", "handy", "when", "something", "causes", "desync", "between", "termbox", "s", "understanding", "of", "a", "terminal", "buffer", "and", "the", "reality", ".", "Such", "as", "a", "third", "party", "process", ".", "Sync", "forces", "a", "complete", "resync", "between", "the", "termbox", "and", "a", "terminal", "it", "may", "not", "be", "visually", "pretty", "though", "." ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/api.go#L489-L497
train
tus/tusd
metrics.go
incRequestsTotal
func (m Metrics) incRequestsTotal(method string) { if ptr, ok := m.RequestsTotal[method]; ok { atomic.AddUint64(ptr, 1) } }
go
func (m Metrics) incRequestsTotal(method string) { if ptr, ok := m.RequestsTotal[method]; ok { atomic.AddUint64(ptr, 1) } }
[ "func", "(", "m", "Metrics", ")", "incRequestsTotal", "(", "method", "string", ")", "{", "if", "ptr", ",", "ok", ":=", "m", ".", "RequestsTotal", "[", "method", "]", ";", "ok", "{", "atomic", ".", "AddUint64", "(", "ptr", ",", "1", ")", "\n", "}", "\n", "}" ]
// incRequestsTotal increases the counter for this request method atomically by // one. The method must be one of GET, HEAD, POST, PATCH, DELETE.
[ "incRequestsTotal", "increases", "the", "counter", "for", "this", "request", "method", "atomically", "by", "one", ".", "The", "method", "must", "be", "one", "of", "GET", "HEAD", "POST", "PATCH", "DELETE", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/metrics.go#L27-L31
train
tus/tusd
metrics.go
incErrorsTotal
func (m Metrics) incErrorsTotal(err HTTPError) { ptr := m.ErrorsTotal.retrievePointerFor(err) atomic.AddUint64(ptr, 1) }
go
func (m Metrics) incErrorsTotal(err HTTPError) { ptr := m.ErrorsTotal.retrievePointerFor(err) atomic.AddUint64(ptr, 1) }
[ "func", "(", "m", "Metrics", ")", "incErrorsTotal", "(", "err", "HTTPError", ")", "{", "ptr", ":=", "m", ".", "ErrorsTotal", ".", "retrievePointerFor", "(", "err", ")", "\n", "atomic", ".", "AddUint64", "(", "ptr", ",", "1", ")", "\n", "}" ]
// incErrorsTotal increases the counter for this error atomically by one.
[ "incErrorsTotal", "increases", "the", "counter", "for", "this", "error", "atomically", "by", "one", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/metrics.go#L34-L37
train
tus/tusd
metrics.go
incBytesReceived
func (m Metrics) incBytesReceived(delta uint64) { atomic.AddUint64(m.BytesReceived, delta) }
go
func (m Metrics) incBytesReceived(delta uint64) { atomic.AddUint64(m.BytesReceived, delta) }
[ "func", "(", "m", "Metrics", ")", "incBytesReceived", "(", "delta", "uint64", ")", "{", "atomic", ".", "AddUint64", "(", "m", ".", "BytesReceived", ",", "delta", ")", "\n", "}" ]
// incBytesReceived increases the number of received bytes atomically be the // specified number.
[ "incBytesReceived", "increases", "the", "number", "of", "received", "bytes", "atomically", "be", "the", "specified", "number", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/metrics.go#L41-L43
train
tus/tusd
metrics.go
Load
func (e *ErrorsTotalMap) Load() map[HTTPError]*uint64 { m := make(map[HTTPError]*uint64, len(e.counter)) e.lock.RLock() for err, ptr := range e.counter { httpErr := NewHTTPError(errors.New(err.Message), err.StatusCode) m[httpErr] = ptr } e.lock.RUnlock() return m }
go
func (e *ErrorsTotalMap) Load() map[HTTPError]*uint64 { m := make(map[HTTPError]*uint64, len(e.counter)) e.lock.RLock() for err, ptr := range e.counter { httpErr := NewHTTPError(errors.New(err.Message), err.StatusCode) m[httpErr] = ptr } e.lock.RUnlock() return m }
[ "func", "(", "e", "*", "ErrorsTotalMap", ")", "Load", "(", ")", "map", "[", "HTTPError", "]", "*", "uint64", "{", "m", ":=", "make", "(", "map", "[", "HTTPError", "]", "*", "uint64", ",", "len", "(", "e", ".", "counter", ")", ")", "\n", "e", ".", "lock", ".", "RLock", "(", ")", "\n", "for", "err", ",", "ptr", ":=", "range", "e", ".", "counter", "{", "httpErr", ":=", "NewHTTPError", "(", "errors", ".", "New", "(", "err", ".", "Message", ")", ",", "err", ".", "StatusCode", ")", "\n", "m", "[", "httpErr", "]", "=", "ptr", "\n", "}", "\n", "e", ".", "lock", ".", "RUnlock", "(", ")", "\n", "return", "m", "\n", "}" ]
// Load retrieves the map of the counter pointers atomically
[ "Load", "retrieves", "the", "map", "of", "the", "counter", "pointers", "atomically" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/metrics.go#L127-L137
train
tus/tusd
etcd3locker/locker_options.go
Prefix
func (l *LockerOptions) Prefix() string { prefix := l.prefix if !strings.HasPrefix(prefix, "/") { prefix = "/" + prefix } if prefix == "" { return DefaultPrefix } else { return prefix } }
go
func (l *LockerOptions) Prefix() string { prefix := l.prefix if !strings.HasPrefix(prefix, "/") { prefix = "/" + prefix } if prefix == "" { return DefaultPrefix } else { return prefix } }
[ "func", "(", "l", "*", "LockerOptions", ")", "Prefix", "(", ")", "string", "{", "prefix", ":=", "l", ".", "prefix", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "prefix", ",", "\"/\"", ")", "{", "prefix", "=", "\"/\"", "+", "prefix", "\n", "}", "\n", "if", "prefix", "==", "\"\"", "{", "return", "DefaultPrefix", "\n", "}", "else", "{", "return", "prefix", "\n", "}", "\n", "}" ]
// Returns the string prefix used to store keys in etcd3
[ "Returns", "the", "string", "prefix", "used", "to", "store", "keys", "in", "etcd3" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/etcd3locker/locker_options.go#L45-L56
train
tus/tusd
limitedstore/limitedstore.go
New
func New(storeSize int64, dataStore tusd.DataStore, terminater tusd.TerminaterDataStore) *LimitedStore { return &LimitedStore{ StoreSize: storeSize, DataStore: dataStore, terminater: terminater, uploads: make(map[string]int64), mutex: new(sync.Mutex), } }
go
func New(storeSize int64, dataStore tusd.DataStore, terminater tusd.TerminaterDataStore) *LimitedStore { return &LimitedStore{ StoreSize: storeSize, DataStore: dataStore, terminater: terminater, uploads: make(map[string]int64), mutex: new(sync.Mutex), } }
[ "func", "New", "(", "storeSize", "int64", ",", "dataStore", "tusd", ".", "DataStore", ",", "terminater", "tusd", ".", "TerminaterDataStore", ")", "*", "LimitedStore", "{", "return", "&", "LimitedStore", "{", "StoreSize", ":", "storeSize", ",", "DataStore", ":", "dataStore", ",", "terminater", ":", "terminater", ",", "uploads", ":", "make", "(", "map", "[", "string", "]", "int64", ")", ",", "mutex", ":", "new", "(", "sync", ".", "Mutex", ")", ",", "}", "\n", "}" ]
// New creates a new limited store with the given size as the maximum storage // size. The wrapped data store needs to implement the TerminaterDataStore // interface, in order to provide the required Terminate method.
[ "New", "creates", "a", "new", "limited", "store", "with", "the", "given", "size", "as", "the", "maximum", "storage", "size", ".", "The", "wrapped", "data", "store", "needs", "to", "implement", "the", "TerminaterDataStore", "interface", "in", "order", "to", "provide", "the", "required", "Terminate", "method", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/limitedstore/limitedstore.go#L52-L60
train
tus/tusd
limitedstore/limitedstore.go
ensureSpace
func (store *LimitedStore) ensureSpace(size int64) error { if (store.usedSize + size) <= store.StoreSize { // Enough space is available to store the new upload return nil } sortedUploads := make(pairlist, len(store.uploads)) i := 0 for u, h := range store.uploads { sortedUploads[i] = pair{u, h} i++ } sort.Sort(sort.Reverse(sortedUploads)) // Forward traversal through the uploads in terms of size, biggest upload first for _, k := range sortedUploads { id := k.key if err := store.terminate(id); err != nil { return err } if (store.usedSize + size) <= store.StoreSize { // Enough space has been freed to store the new upload return nil } } return nil }
go
func (store *LimitedStore) ensureSpace(size int64) error { if (store.usedSize + size) <= store.StoreSize { // Enough space is available to store the new upload return nil } sortedUploads := make(pairlist, len(store.uploads)) i := 0 for u, h := range store.uploads { sortedUploads[i] = pair{u, h} i++ } sort.Sort(sort.Reverse(sortedUploads)) // Forward traversal through the uploads in terms of size, biggest upload first for _, k := range sortedUploads { id := k.key if err := store.terminate(id); err != nil { return err } if (store.usedSize + size) <= store.StoreSize { // Enough space has been freed to store the new upload return nil } } return nil }
[ "func", "(", "store", "*", "LimitedStore", ")", "ensureSpace", "(", "size", "int64", ")", "error", "{", "if", "(", "store", ".", "usedSize", "+", "size", ")", "<=", "store", ".", "StoreSize", "{", "return", "nil", "\n", "}", "\n", "sortedUploads", ":=", "make", "(", "pairlist", ",", "len", "(", "store", ".", "uploads", ")", ")", "\n", "i", ":=", "0", "\n", "for", "u", ",", "h", ":=", "range", "store", ".", "uploads", "{", "sortedUploads", "[", "i", "]", "=", "pair", "{", "u", ",", "h", "}", "\n", "i", "++", "\n", "}", "\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "sortedUploads", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "sortedUploads", "{", "id", ":=", "k", ".", "key", "\n", "if", "err", ":=", "store", ".", "terminate", "(", "id", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "(", "store", ".", "usedSize", "+", "size", ")", "<=", "store", ".", "StoreSize", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Ensure enough space is available to store an upload of the specified size. // It will terminate uploads until enough space is freed.
[ "Ensure", "enough", "space", "is", "available", "to", "store", "an", "upload", "of", "the", "specified", "size", ".", "It", "will", "terminate", "uploads", "until", "enough", "space", "is", "freed", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/limitedstore/limitedstore.go#L111-L140
train
tus/tusd
filestore/filestore.go
newLock
func (store FileStore) newLock(id string) (lockfile.Lockfile, error) { path, err := filepath.Abs(filepath.Join(store.Path, id+".lock")) if err != nil { return lockfile.Lockfile(""), err } // We use Lockfile directly instead of lockfile.New to bypass the unnecessary // check whether the provided path is absolute since we just resolved it // on our own. return lockfile.Lockfile(path), nil }
go
func (store FileStore) newLock(id string) (lockfile.Lockfile, error) { path, err := filepath.Abs(filepath.Join(store.Path, id+".lock")) if err != nil { return lockfile.Lockfile(""), err } // We use Lockfile directly instead of lockfile.New to bypass the unnecessary // check whether the provided path is absolute since we just resolved it // on our own. return lockfile.Lockfile(path), nil }
[ "func", "(", "store", "FileStore", ")", "newLock", "(", "id", "string", ")", "(", "lockfile", ".", "Lockfile", ",", "error", ")", "{", "path", ",", "err", ":=", "filepath", ".", "Abs", "(", "filepath", ".", "Join", "(", "store", ".", "Path", ",", "id", "+", "\".lock\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "lockfile", ".", "Lockfile", "(", "\"\"", ")", ",", "err", "\n", "}", "\n", "return", "lockfile", ".", "Lockfile", "(", "path", ")", ",", "nil", "\n", "}" ]
// newLock contructs a new Lockfile instance.
[ "newLock", "contructs", "a", "new", "Lockfile", "instance", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/filestore/filestore.go#L189-L199
train
tus/tusd
filestore/filestore.go
binPath
func (store FileStore) binPath(id string) string { return filepath.Join(store.Path, id+".bin") }
go
func (store FileStore) binPath(id string) string { return filepath.Join(store.Path, id+".bin") }
[ "func", "(", "store", "FileStore", ")", "binPath", "(", "id", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "store", ".", "Path", ",", "id", "+", "\".bin\"", ")", "\n", "}" ]
// binPath returns the path to the .bin storing the binary data.
[ "binPath", "returns", "the", "path", "to", "the", ".", "bin", "storing", "the", "binary", "data", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/filestore/filestore.go#L202-L204
train
tus/tusd
filestore/filestore.go
infoPath
func (store FileStore) infoPath(id string) string { return filepath.Join(store.Path, id+".info") }
go
func (store FileStore) infoPath(id string) string { return filepath.Join(store.Path, id+".info") }
[ "func", "(", "store", "FileStore", ")", "infoPath", "(", "id", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "store", ".", "Path", ",", "id", "+", "\".info\"", ")", "\n", "}" ]
// infoPath returns the path to the .info file storing the file's info.
[ "infoPath", "returns", "the", "path", "to", "the", ".", "info", "file", "storing", "the", "file", "s", "info", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/filestore/filestore.go#L207-L209
train
tus/tusd
filestore/filestore.go
writeInfo
func (store FileStore) writeInfo(id string, info tusd.FileInfo) error { data, err := json.Marshal(info) if err != nil { return err } return ioutil.WriteFile(store.infoPath(id), data, defaultFilePerm) }
go
func (store FileStore) writeInfo(id string, info tusd.FileInfo) error { data, err := json.Marshal(info) if err != nil { return err } return ioutil.WriteFile(store.infoPath(id), data, defaultFilePerm) }
[ "func", "(", "store", "FileStore", ")", "writeInfo", "(", "id", "string", ",", "info", "tusd", ".", "FileInfo", ")", "error", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "info", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ioutil", ".", "WriteFile", "(", "store", ".", "infoPath", "(", "id", ")", ",", "data", ",", "defaultFilePerm", ")", "\n", "}" ]
// writeInfo updates the entire information. Everything will be overwritten.
[ "writeInfo", "updates", "the", "entire", "information", ".", "Everything", "will", "be", "overwritten", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/filestore/filestore.go#L212-L218
train
tus/tusd
consullocker/consullocker.go
New
func New(client *consul.Client) *ConsulLocker { return &ConsulLocker{ Client: client, locks: make(map[string]*consul.Lock), mutex: new(sync.RWMutex), } }
go
func New(client *consul.Client) *ConsulLocker { return &ConsulLocker{ Client: client, locks: make(map[string]*consul.Lock), mutex: new(sync.RWMutex), } }
[ "func", "New", "(", "client", "*", "consul", ".", "Client", ")", "*", "ConsulLocker", "{", "return", "&", "ConsulLocker", "{", "Client", ":", "client", ",", "locks", ":", "make", "(", "map", "[", "string", "]", "*", "consul", ".", "Lock", ")", ",", "mutex", ":", "new", "(", "sync", ".", "RWMutex", ")", ",", "}", "\n", "}" ]
// New constructs a new locker using the provided client.
[ "New", "constructs", "a", "new", "locker", "using", "the", "provided", "client", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/consullocker/consullocker.go#L40-L46
train
tus/tusd
unrouted_handler.go
Middleware
func (handler *UnroutedHandler) Middleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Allow overriding the HTTP method. The reason for this is // that some libraries/environments to not support PATCH and // DELETE requests, e.g. Flash in a browser and parts of Java if newMethod := r.Header.Get("X-HTTP-Method-Override"); newMethod != "" { r.Method = newMethod } handler.log("RequestIncoming", "method", r.Method, "path", r.URL.Path) handler.Metrics.incRequestsTotal(r.Method) header := w.Header() if origin := r.Header.Get("Origin"); origin != "" { header.Set("Access-Control-Allow-Origin", origin) if r.Method == "OPTIONS" { // Preflight request header.Add("Access-Control-Allow-Methods", "POST, GET, HEAD, PATCH, DELETE, OPTIONS") header.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata, Upload-Defer-Length, Upload-Concat") header.Set("Access-Control-Max-Age", "86400") } else { // Actual request header.Add("Access-Control-Expose-Headers", "Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, Upload-Defer-Length, Upload-Concat") } } // Set current version used by the server header.Set("Tus-Resumable", "1.0.0") // Add nosniff to all responses https://golang.org/src/net/http/server.go#L1429 header.Set("X-Content-Type-Options", "nosniff") // Set appropriated headers in case of OPTIONS method allowing protocol // discovery and end with an 204 No Content if r.Method == "OPTIONS" { if handler.config.MaxSize > 0 { header.Set("Tus-Max-Size", strconv.FormatInt(handler.config.MaxSize, 10)) } header.Set("Tus-Version", "1.0.0") header.Set("Tus-Extension", handler.extensions) // Although the 204 No Content status code is a better fit in this case, // since we do not have a response body included, we cannot use it here // as some browsers only accept 200 OK as successful response to a // preflight request. If we send them the 204 No Content the response // will be ignored or interpreted as a rejection. // For example, the Presto engine, which is used in older versions of // Opera, Opera Mobile and Opera Mini, handles CORS this way. handler.sendResp(w, r, http.StatusOK) return } // Test if the version sent by the client is supported // GET methods are not checked since a browser may visit this URL and does // not include this header. This request is not part of the specification. if r.Method != "GET" && r.Header.Get("Tus-Resumable") != "1.0.0" { handler.sendError(w, r, ErrUnsupportedVersion) return } // Proceed with routing the request h.ServeHTTP(w, r) }) }
go
func (handler *UnroutedHandler) Middleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Allow overriding the HTTP method. The reason for this is // that some libraries/environments to not support PATCH and // DELETE requests, e.g. Flash in a browser and parts of Java if newMethod := r.Header.Get("X-HTTP-Method-Override"); newMethod != "" { r.Method = newMethod } handler.log("RequestIncoming", "method", r.Method, "path", r.URL.Path) handler.Metrics.incRequestsTotal(r.Method) header := w.Header() if origin := r.Header.Get("Origin"); origin != "" { header.Set("Access-Control-Allow-Origin", origin) if r.Method == "OPTIONS" { // Preflight request header.Add("Access-Control-Allow-Methods", "POST, GET, HEAD, PATCH, DELETE, OPTIONS") header.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata, Upload-Defer-Length, Upload-Concat") header.Set("Access-Control-Max-Age", "86400") } else { // Actual request header.Add("Access-Control-Expose-Headers", "Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, Upload-Defer-Length, Upload-Concat") } } // Set current version used by the server header.Set("Tus-Resumable", "1.0.0") // Add nosniff to all responses https://golang.org/src/net/http/server.go#L1429 header.Set("X-Content-Type-Options", "nosniff") // Set appropriated headers in case of OPTIONS method allowing protocol // discovery and end with an 204 No Content if r.Method == "OPTIONS" { if handler.config.MaxSize > 0 { header.Set("Tus-Max-Size", strconv.FormatInt(handler.config.MaxSize, 10)) } header.Set("Tus-Version", "1.0.0") header.Set("Tus-Extension", handler.extensions) // Although the 204 No Content status code is a better fit in this case, // since we do not have a response body included, we cannot use it here // as some browsers only accept 200 OK as successful response to a // preflight request. If we send them the 204 No Content the response // will be ignored or interpreted as a rejection. // For example, the Presto engine, which is used in older versions of // Opera, Opera Mobile and Opera Mini, handles CORS this way. handler.sendResp(w, r, http.StatusOK) return } // Test if the version sent by the client is supported // GET methods are not checked since a browser may visit this URL and does // not include this header. This request is not part of the specification. if r.Method != "GET" && r.Header.Get("Tus-Resumable") != "1.0.0" { handler.sendError(w, r, ErrUnsupportedVersion) return } // Proceed with routing the request h.ServeHTTP(w, r) }) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "Middleware", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "newMethod", ":=", "r", ".", "Header", ".", "Get", "(", "\"X-HTTP-Method-Override\"", ")", ";", "newMethod", "!=", "\"\"", "{", "r", ".", "Method", "=", "newMethod", "\n", "}", "\n", "handler", ".", "log", "(", "\"RequestIncoming\"", ",", "\"method\"", ",", "r", ".", "Method", ",", "\"path\"", ",", "r", ".", "URL", ".", "Path", ")", "\n", "handler", ".", "Metrics", ".", "incRequestsTotal", "(", "r", ".", "Method", ")", "\n", "header", ":=", "w", ".", "Header", "(", ")", "\n", "if", "origin", ":=", "r", ".", "Header", ".", "Get", "(", "\"Origin\"", ")", ";", "origin", "!=", "\"\"", "{", "header", ".", "Set", "(", "\"Access-Control-Allow-Origin\"", ",", "origin", ")", "\n", "if", "r", ".", "Method", "==", "\"OPTIONS\"", "{", "header", ".", "Add", "(", "\"Access-Control-Allow-Methods\"", ",", "\"POST, GET, HEAD, PATCH, DELETE, OPTIONS\"", ")", "\n", "header", ".", "Add", "(", "\"Access-Control-Allow-Headers\"", ",", "\"Origin, X-Requested-With, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata, Upload-Defer-Length, Upload-Concat\"", ")", "\n", "header", ".", "Set", "(", "\"Access-Control-Max-Age\"", ",", "\"86400\"", ")", "\n", "}", "else", "{", "header", ".", "Add", "(", "\"Access-Control-Expose-Headers\"", ",", "\"Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, Upload-Defer-Length, Upload-Concat\"", ")", "\n", "}", "\n", "}", "\n", "header", ".", "Set", "(", "\"Tus-Resumable\"", ",", "\"1.0.0\"", ")", "\n", "header", ".", "Set", "(", "\"X-Content-Type-Options\"", ",", "\"nosniff\"", ")", "\n", "if", "r", ".", "Method", "==", "\"OPTIONS\"", "{", "if", "handler", ".", "config", ".", "MaxSize", ">", "0", "{", "header", ".", "Set", "(", "\"Tus-Max-Size\"", ",", "strconv", ".", "FormatInt", "(", "handler", ".", "config", ".", "MaxSize", ",", "10", ")", ")", "\n", "}", "\n", "header", ".", "Set", "(", "\"Tus-Version\"", ",", "\"1.0.0\"", ")", "\n", "header", ".", "Set", "(", "\"Tus-Extension\"", ",", "handler", ".", "extensions", ")", "\n", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusOK", ")", "\n", "return", "\n", "}", "\n", "if", "r", ".", "Method", "!=", "\"GET\"", "&&", "r", ".", "Header", ".", "Get", "(", "\"Tus-Resumable\"", ")", "!=", "\"1.0.0\"", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "ErrUnsupportedVersion", ")", "\n", "return", "\n", "}", "\n", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// Middleware checks various aspects of the request and ensures that it // conforms with the spec. Also handles method overriding for clients which // cannot make PATCH AND DELETE requests. If you are using the tusd handlers // directly you will need to wrap at least the POST and PATCH endpoints in // this middleware.
[ "Middleware", "checks", "various", "aspects", "of", "the", "request", "and", "ensures", "that", "it", "conforms", "with", "the", "spec", ".", "Also", "handles", "method", "overriding", "for", "clients", "which", "cannot", "make", "PATCH", "AND", "DELETE", "requests", ".", "If", "you", "are", "using", "the", "tusd", "handlers", "directly", "you", "will", "need", "to", "wrap", "at", "least", "the", "POST", "and", "PATCH", "endpoints", "in", "this", "middleware", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L161-L229
train
tus/tusd
unrouted_handler.go
HeadFile
func (handler *UnroutedHandler) HeadFile(w http.ResponseWriter, r *http.Request) { id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } info, err := handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } // Add Upload-Concat header if possible if info.IsPartial { w.Header().Set("Upload-Concat", "partial") } if info.IsFinal { v := "final;" for _, uploadID := range info.PartialUploads { v += handler.absFileURL(r, uploadID) + " " } // Remove trailing space v = v[:len(v)-1] w.Header().Set("Upload-Concat", v) } if len(info.MetaData) != 0 { w.Header().Set("Upload-Metadata", SerializeMetadataHeader(info.MetaData)) } if info.SizeIsDeferred { w.Header().Set("Upload-Defer-Length", UploadLengthDeferred) } else { w.Header().Set("Upload-Length", strconv.FormatInt(info.Size, 10)) } w.Header().Set("Cache-Control", "no-store") w.Header().Set("Upload-Offset", strconv.FormatInt(info.Offset, 10)) handler.sendResp(w, r, http.StatusOK) }
go
func (handler *UnroutedHandler) HeadFile(w http.ResponseWriter, r *http.Request) { id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } info, err := handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } // Add Upload-Concat header if possible if info.IsPartial { w.Header().Set("Upload-Concat", "partial") } if info.IsFinal { v := "final;" for _, uploadID := range info.PartialUploads { v += handler.absFileURL(r, uploadID) + " " } // Remove trailing space v = v[:len(v)-1] w.Header().Set("Upload-Concat", v) } if len(info.MetaData) != 0 { w.Header().Set("Upload-Metadata", SerializeMetadataHeader(info.MetaData)) } if info.SizeIsDeferred { w.Header().Set("Upload-Defer-Length", UploadLengthDeferred) } else { w.Header().Set("Upload-Length", strconv.FormatInt(info.Size, 10)) } w.Header().Set("Cache-Control", "no-store") w.Header().Set("Upload-Offset", strconv.FormatInt(info.Offset, 10)) handler.sendResp(w, r, http.StatusOK) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "HeadFile", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "id", ",", "err", ":=", "extractIDFromPath", "(", "r", ".", "URL", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "handler", ".", "composer", ".", "UsesLocker", "{", "locker", ":=", "handler", ".", "composer", ".", "Locker", "\n", "if", "err", ":=", "locker", ".", "LockUpload", "(", "id", ")", ";", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "locker", ".", "UnlockUpload", "(", "id", ")", "\n", "}", "\n", "info", ",", "err", ":=", "handler", ".", "composer", ".", "Core", ".", "GetInfo", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "info", ".", "IsPartial", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Upload-Concat\"", ",", "\"partial\"", ")", "\n", "}", "\n", "if", "info", ".", "IsFinal", "{", "v", ":=", "\"final;\"", "\n", "for", "_", ",", "uploadID", ":=", "range", "info", ".", "PartialUploads", "{", "v", "+=", "handler", ".", "absFileURL", "(", "r", ",", "uploadID", ")", "+", "\" \"", "\n", "}", "\n", "v", "=", "v", "[", ":", "len", "(", "v", ")", "-", "1", "]", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Upload-Concat\"", ",", "v", ")", "\n", "}", "\n", "if", "len", "(", "info", ".", "MetaData", ")", "!=", "0", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Upload-Metadata\"", ",", "SerializeMetadataHeader", "(", "info", ".", "MetaData", ")", ")", "\n", "}", "\n", "if", "info", ".", "SizeIsDeferred", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Upload-Defer-Length\"", ",", "UploadLengthDeferred", ")", "\n", "}", "else", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Upload-Length\"", ",", "strconv", ".", "FormatInt", "(", "info", ".", "Size", ",", "10", ")", ")", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Cache-Control\"", ",", "\"no-store\"", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Upload-Offset\"", ",", "strconv", ".", "FormatInt", "(", "info", ".", "Offset", ",", "10", ")", ")", "\n", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusOK", ")", "\n", "}" ]
// HeadFile returns the length and offset for the HEAD request
[ "HeadFile", "returns", "the", "length", "and", "offset", "for", "the", "HEAD", "request" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L356-L409
train
tus/tusd
unrouted_handler.go
writeChunk
func (handler *UnroutedHandler) writeChunk(id string, info FileInfo, w http.ResponseWriter, r *http.Request) error { // Get Content-Length if possible length := r.ContentLength offset := info.Offset // Test if this upload fits into the file's size if !info.SizeIsDeferred && offset+length > info.Size { return ErrSizeExceeded } maxSize := info.Size - offset // If the upload's length is deferred and the PATCH request does not contain the Content-Length // header (which is allowed if 'Transfer-Encoding: chunked' is used), we still need to set limits for // the body size. if info.SizeIsDeferred { if handler.config.MaxSize > 0 { // Ensure that the upload does not exceed the maximum upload size maxSize = handler.config.MaxSize - offset } else { // If no upload limit is given, we allow arbitrary sizes maxSize = math.MaxInt64 } } if length > 0 { maxSize = length } handler.log("ChunkWriteStart", "id", id, "maxSize", i64toa(maxSize), "offset", i64toa(offset)) var bytesWritten int64 // Prevent a nil pointer dereference when accessing the body which may not be // available in the case of a malicious request. if r.Body != nil { // Limit the data read from the request's body to the allowed maximum reader := io.LimitReader(r.Body, maxSize) if handler.config.NotifyUploadProgress { var stop chan<- struct{} reader, stop = handler.sendProgressMessages(info, reader) defer close(stop) } var err error bytesWritten, err = handler.composer.Core.WriteChunk(id, offset, reader) if err != nil { return err } } handler.log("ChunkWriteComplete", "id", id, "bytesWritten", i64toa(bytesWritten)) // Send new offset to client newOffset := offset + bytesWritten w.Header().Set("Upload-Offset", strconv.FormatInt(newOffset, 10)) handler.Metrics.incBytesReceived(uint64(bytesWritten)) info.Offset = newOffset return handler.finishUploadIfComplete(info) }
go
func (handler *UnroutedHandler) writeChunk(id string, info FileInfo, w http.ResponseWriter, r *http.Request) error { // Get Content-Length if possible length := r.ContentLength offset := info.Offset // Test if this upload fits into the file's size if !info.SizeIsDeferred && offset+length > info.Size { return ErrSizeExceeded } maxSize := info.Size - offset // If the upload's length is deferred and the PATCH request does not contain the Content-Length // header (which is allowed if 'Transfer-Encoding: chunked' is used), we still need to set limits for // the body size. if info.SizeIsDeferred { if handler.config.MaxSize > 0 { // Ensure that the upload does not exceed the maximum upload size maxSize = handler.config.MaxSize - offset } else { // If no upload limit is given, we allow arbitrary sizes maxSize = math.MaxInt64 } } if length > 0 { maxSize = length } handler.log("ChunkWriteStart", "id", id, "maxSize", i64toa(maxSize), "offset", i64toa(offset)) var bytesWritten int64 // Prevent a nil pointer dereference when accessing the body which may not be // available in the case of a malicious request. if r.Body != nil { // Limit the data read from the request's body to the allowed maximum reader := io.LimitReader(r.Body, maxSize) if handler.config.NotifyUploadProgress { var stop chan<- struct{} reader, stop = handler.sendProgressMessages(info, reader) defer close(stop) } var err error bytesWritten, err = handler.composer.Core.WriteChunk(id, offset, reader) if err != nil { return err } } handler.log("ChunkWriteComplete", "id", id, "bytesWritten", i64toa(bytesWritten)) // Send new offset to client newOffset := offset + bytesWritten w.Header().Set("Upload-Offset", strconv.FormatInt(newOffset, 10)) handler.Metrics.incBytesReceived(uint64(bytesWritten)) info.Offset = newOffset return handler.finishUploadIfComplete(info) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "writeChunk", "(", "id", "string", ",", "info", "FileInfo", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "error", "{", "length", ":=", "r", ".", "ContentLength", "\n", "offset", ":=", "info", ".", "Offset", "\n", "if", "!", "info", ".", "SizeIsDeferred", "&&", "offset", "+", "length", ">", "info", ".", "Size", "{", "return", "ErrSizeExceeded", "\n", "}", "\n", "maxSize", ":=", "info", ".", "Size", "-", "offset", "\n", "if", "info", ".", "SizeIsDeferred", "{", "if", "handler", ".", "config", ".", "MaxSize", ">", "0", "{", "maxSize", "=", "handler", ".", "config", ".", "MaxSize", "-", "offset", "\n", "}", "else", "{", "maxSize", "=", "math", ".", "MaxInt64", "\n", "}", "\n", "}", "\n", "if", "length", ">", "0", "{", "maxSize", "=", "length", "\n", "}", "\n", "handler", ".", "log", "(", "\"ChunkWriteStart\"", ",", "\"id\"", ",", "id", ",", "\"maxSize\"", ",", "i64toa", "(", "maxSize", ")", ",", "\"offset\"", ",", "i64toa", "(", "offset", ")", ")", "\n", "var", "bytesWritten", "int64", "\n", "if", "r", ".", "Body", "!=", "nil", "{", "reader", ":=", "io", ".", "LimitReader", "(", "r", ".", "Body", ",", "maxSize", ")", "\n", "if", "handler", ".", "config", ".", "NotifyUploadProgress", "{", "var", "stop", "chan", "<-", "struct", "{", "}", "\n", "reader", ",", "stop", "=", "handler", ".", "sendProgressMessages", "(", "info", ",", "reader", ")", "\n", "defer", "close", "(", "stop", ")", "\n", "}", "\n", "var", "err", "error", "\n", "bytesWritten", ",", "err", "=", "handler", ".", "composer", ".", "Core", ".", "WriteChunk", "(", "id", ",", "offset", ",", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "handler", ".", "log", "(", "\"ChunkWriteComplete\"", ",", "\"id\"", ",", "id", ",", "\"bytesWritten\"", ",", "i64toa", "(", "bytesWritten", ")", ")", "\n", "newOffset", ":=", "offset", "+", "bytesWritten", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Upload-Offset\"", ",", "strconv", ".", "FormatInt", "(", "newOffset", ",", "10", ")", ")", "\n", "handler", ".", "Metrics", ".", "incBytesReceived", "(", "uint64", "(", "bytesWritten", ")", ")", "\n", "info", ".", "Offset", "=", "newOffset", "\n", "return", "handler", ".", "finishUploadIfComplete", "(", "info", ")", "\n", "}" ]
// writeChunk reads the body from the requests r and appends it to the upload // with the corresponding id. Afterwards, it will set the necessary response // headers but will not send the response.
[ "writeChunk", "reads", "the", "body", "from", "the", "requests", "r", "and", "appends", "it", "to", "the", "upload", "with", "the", "corresponding", "id", ".", "Afterwards", "it", "will", "set", "the", "necessary", "response", "headers", "but", "will", "not", "send", "the", "response", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L502-L560
train
tus/tusd
unrouted_handler.go
GetFile
func (handler *UnroutedHandler) GetFile(w http.ResponseWriter, r *http.Request) { if !handler.composer.UsesGetReader { handler.sendError(w, r, ErrNotImplemented) return } id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } info, err := handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } // Set headers before sending responses w.Header().Set("Content-Length", strconv.FormatInt(info.Offset, 10)) contentType, contentDisposition := filterContentType(info) w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Disposition", contentDisposition) // If no data has been uploaded yet, respond with an empty "204 No Content" status. if info.Offset == 0 { handler.sendResp(w, r, http.StatusNoContent) return } src, err := handler.composer.GetReader.GetReader(id) if err != nil { handler.sendError(w, r, err) return } handler.sendResp(w, r, http.StatusOK) io.Copy(w, src) // Try to close the reader if the io.Closer interface is implemented if closer, ok := src.(io.Closer); ok { closer.Close() } }
go
func (handler *UnroutedHandler) GetFile(w http.ResponseWriter, r *http.Request) { if !handler.composer.UsesGetReader { handler.sendError(w, r, ErrNotImplemented) return } id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } info, err := handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } // Set headers before sending responses w.Header().Set("Content-Length", strconv.FormatInt(info.Offset, 10)) contentType, contentDisposition := filterContentType(info) w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Disposition", contentDisposition) // If no data has been uploaded yet, respond with an empty "204 No Content" status. if info.Offset == 0 { handler.sendResp(w, r, http.StatusNoContent) return } src, err := handler.composer.GetReader.GetReader(id) if err != nil { handler.sendError(w, r, err) return } handler.sendResp(w, r, http.StatusOK) io.Copy(w, src) // Try to close the reader if the io.Closer interface is implemented if closer, ok := src.(io.Closer); ok { closer.Close() } }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "GetFile", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "!", "handler", ".", "composer", ".", "UsesGetReader", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "ErrNotImplemented", ")", "\n", "return", "\n", "}", "\n", "id", ",", "err", ":=", "extractIDFromPath", "(", "r", ".", "URL", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "handler", ".", "composer", ".", "UsesLocker", "{", "locker", ":=", "handler", ".", "composer", ".", "Locker", "\n", "if", "err", ":=", "locker", ".", "LockUpload", "(", "id", ")", ";", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "locker", ".", "UnlockUpload", "(", "id", ")", "\n", "}", "\n", "info", ",", "err", ":=", "handler", ".", "composer", ".", "Core", ".", "GetInfo", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Length\"", ",", "strconv", ".", "FormatInt", "(", "info", ".", "Offset", ",", "10", ")", ")", "\n", "contentType", ",", "contentDisposition", ":=", "filterContentType", "(", "info", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "contentType", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Disposition\"", ",", "contentDisposition", ")", "\n", "if", "info", ".", "Offset", "==", "0", "{", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusNoContent", ")", "\n", "return", "\n", "}", "\n", "src", ",", "err", ":=", "handler", ".", "composer", ".", "GetReader", ".", "GetReader", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusOK", ")", "\n", "io", ".", "Copy", "(", "w", ",", "src", ")", "\n", "if", "closer", ",", "ok", ":=", "src", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "closer", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// GetFile handles requests to download a file using a GET request. This is not // part of the specification.
[ "GetFile", "handles", "requests", "to", "download", "a", "file", "using", "a", "GET", "request", ".", "This", "is", "not", "part", "of", "the", "specification", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L588-L642
train
tus/tusd
unrouted_handler.go
DelFile
func (handler *UnroutedHandler) DelFile(w http.ResponseWriter, r *http.Request) { // Abort the request handling if the required interface is not implemented if !handler.composer.UsesTerminater { handler.sendError(w, r, ErrNotImplemented) return } id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } var info FileInfo if handler.config.NotifyTerminatedUploads { info, err = handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } } err = handler.composer.Terminater.Terminate(id) if err != nil { handler.sendError(w, r, err) return } handler.sendResp(w, r, http.StatusNoContent) if handler.config.NotifyTerminatedUploads { handler.TerminatedUploads <- info } handler.Metrics.incUploadsTerminated() }
go
func (handler *UnroutedHandler) DelFile(w http.ResponseWriter, r *http.Request) { // Abort the request handling if the required interface is not implemented if !handler.composer.UsesTerminater { handler.sendError(w, r, ErrNotImplemented) return } id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } var info FileInfo if handler.config.NotifyTerminatedUploads { info, err = handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } } err = handler.composer.Terminater.Terminate(id) if err != nil { handler.sendError(w, r, err) return } handler.sendResp(w, r, http.StatusNoContent) if handler.config.NotifyTerminatedUploads { handler.TerminatedUploads <- info } handler.Metrics.incUploadsTerminated() }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "DelFile", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "!", "handler", ".", "composer", ".", "UsesTerminater", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "ErrNotImplemented", ")", "\n", "return", "\n", "}", "\n", "id", ",", "err", ":=", "extractIDFromPath", "(", "r", ".", "URL", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "handler", ".", "composer", ".", "UsesLocker", "{", "locker", ":=", "handler", ".", "composer", ".", "Locker", "\n", "if", "err", ":=", "locker", ".", "LockUpload", "(", "id", ")", ";", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "locker", ".", "UnlockUpload", "(", "id", ")", "\n", "}", "\n", "var", "info", "FileInfo", "\n", "if", "handler", ".", "config", ".", "NotifyTerminatedUploads", "{", "info", ",", "err", "=", "handler", ".", "composer", ".", "Core", ".", "GetInfo", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "err", "=", "handler", ".", "composer", ".", "Terminater", ".", "Terminate", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusNoContent", ")", "\n", "if", "handler", ".", "config", ".", "NotifyTerminatedUploads", "{", "handler", ".", "TerminatedUploads", "<-", "info", "\n", "}", "\n", "handler", ".", "Metrics", ".", "incUploadsTerminated", "(", ")", "\n", "}" ]
// DelFile terminates an upload permanently.
[ "DelFile", "terminates", "an", "upload", "permanently", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L706-L751
train
tus/tusd
unrouted_handler.go
sendError
func (handler *UnroutedHandler) sendError(w http.ResponseWriter, r *http.Request, err error) { // Interpret os.ErrNotExist as 404 Not Found if os.IsNotExist(err) { err = ErrNotFound } // Errors for read timeouts contain too much information which is not // necessary for us and makes grouping for the metrics harder. The error // message looks like: read tcp 127.0.0.1:1080->127.0.0.1:53673: i/o timeout // Therefore, we use a common error message for all of them. if netErr, ok := err.(net.Error); ok && netErr.Timeout() { err = errors.New("read tcp: i/o timeout") } statusErr, ok := err.(HTTPError) if !ok { statusErr = NewHTTPError(err, http.StatusInternalServerError) } reason := append(statusErr.Body(), '\n') if r.Method == "HEAD" { reason = nil } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("Content-Length", strconv.Itoa(len(reason))) w.WriteHeader(statusErr.StatusCode()) w.Write(reason) handler.log("ResponseOutgoing", "status", strconv.Itoa(statusErr.StatusCode()), "method", r.Method, "path", r.URL.Path, "error", err.Error()) handler.Metrics.incErrorsTotal(statusErr) }
go
func (handler *UnroutedHandler) sendError(w http.ResponseWriter, r *http.Request, err error) { // Interpret os.ErrNotExist as 404 Not Found if os.IsNotExist(err) { err = ErrNotFound } // Errors for read timeouts contain too much information which is not // necessary for us and makes grouping for the metrics harder. The error // message looks like: read tcp 127.0.0.1:1080->127.0.0.1:53673: i/o timeout // Therefore, we use a common error message for all of them. if netErr, ok := err.(net.Error); ok && netErr.Timeout() { err = errors.New("read tcp: i/o timeout") } statusErr, ok := err.(HTTPError) if !ok { statusErr = NewHTTPError(err, http.StatusInternalServerError) } reason := append(statusErr.Body(), '\n') if r.Method == "HEAD" { reason = nil } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("Content-Length", strconv.Itoa(len(reason))) w.WriteHeader(statusErr.StatusCode()) w.Write(reason) handler.log("ResponseOutgoing", "status", strconv.Itoa(statusErr.StatusCode()), "method", r.Method, "path", r.URL.Path, "error", err.Error()) handler.Metrics.incErrorsTotal(statusErr) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "sendError", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "err", "error", ")", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", "=", "ErrNotFound", "\n", "}", "\n", "if", "netErr", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "ok", "&&", "netErr", ".", "Timeout", "(", ")", "{", "err", "=", "errors", ".", "New", "(", "\"read tcp: i/o timeout\"", ")", "\n", "}", "\n", "statusErr", ",", "ok", ":=", "err", ".", "(", "HTTPError", ")", "\n", "if", "!", "ok", "{", "statusErr", "=", "NewHTTPError", "(", "err", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "reason", ":=", "append", "(", "statusErr", ".", "Body", "(", ")", ",", "'\\n'", ")", "\n", "if", "r", ".", "Method", "==", "\"HEAD\"", "{", "reason", "=", "nil", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"text/plain; charset=utf-8\"", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Length\"", ",", "strconv", ".", "Itoa", "(", "len", "(", "reason", ")", ")", ")", "\n", "w", ".", "WriteHeader", "(", "statusErr", ".", "StatusCode", "(", ")", ")", "\n", "w", ".", "Write", "(", "reason", ")", "\n", "handler", ".", "log", "(", "\"ResponseOutgoing\"", ",", "\"status\"", ",", "strconv", ".", "Itoa", "(", "statusErr", ".", "StatusCode", "(", ")", ")", ",", "\"method\"", ",", "r", ".", "Method", ",", "\"path\"", ",", "r", ".", "URL", ".", "Path", ",", "\"error\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "handler", ".", "Metrics", ".", "incErrorsTotal", "(", "statusErr", ")", "\n", "}" ]
// Send the error in the response body. The status code will be looked up in // ErrStatusCodes. If none is found 500 Internal Error will be used.
[ "Send", "the", "error", "in", "the", "response", "body", ".", "The", "status", "code", "will", "be", "looked", "up", "in", "ErrStatusCodes", ".", "If", "none", "is", "found", "500", "Internal", "Error", "will", "be", "used", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L755-L787
train
tus/tusd
unrouted_handler.go
sendResp
func (handler *UnroutedHandler) sendResp(w http.ResponseWriter, r *http.Request, status int) { w.WriteHeader(status) handler.log("ResponseOutgoing", "status", strconv.Itoa(status), "method", r.Method, "path", r.URL.Path) }
go
func (handler *UnroutedHandler) sendResp(w http.ResponseWriter, r *http.Request, status int) { w.WriteHeader(status) handler.log("ResponseOutgoing", "status", strconv.Itoa(status), "method", r.Method, "path", r.URL.Path) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "sendResp", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "status", "int", ")", "{", "w", ".", "WriteHeader", "(", "status", ")", "\n", "handler", ".", "log", "(", "\"ResponseOutgoing\"", ",", "\"status\"", ",", "strconv", ".", "Itoa", "(", "status", ")", ",", "\"method\"", ",", "r", ".", "Method", ",", "\"path\"", ",", "r", ".", "URL", ".", "Path", ")", "\n", "}" ]
// sendResp writes the header to w with the specified status code.
[ "sendResp", "writes", "the", "header", "to", "w", "with", "the", "specified", "status", "code", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L790-L794
train
tus/tusd
unrouted_handler.go
absFileURL
func (handler *UnroutedHandler) absFileURL(r *http.Request, id string) string { if handler.isBasePathAbs { return handler.basePath + id } // Read origin and protocol from request host, proto := getHostAndProtocol(r, handler.config.RespectForwardedHeaders) url := proto + "://" + host + handler.basePath + id return url }
go
func (handler *UnroutedHandler) absFileURL(r *http.Request, id string) string { if handler.isBasePathAbs { return handler.basePath + id } // Read origin and protocol from request host, proto := getHostAndProtocol(r, handler.config.RespectForwardedHeaders) url := proto + "://" + host + handler.basePath + id return url }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "absFileURL", "(", "r", "*", "http", ".", "Request", ",", "id", "string", ")", "string", "{", "if", "handler", ".", "isBasePathAbs", "{", "return", "handler", ".", "basePath", "+", "id", "\n", "}", "\n", "host", ",", "proto", ":=", "getHostAndProtocol", "(", "r", ",", "handler", ".", "config", ".", "RespectForwardedHeaders", ")", "\n", "url", ":=", "proto", "+", "\"://\"", "+", "host", "+", "handler", ".", "basePath", "+", "id", "\n", "return", "url", "\n", "}" ]
// Make an absolute URLs to the given upload id. If the base path is absolute // it will be prepended else the host and protocol from the request is used.
[ "Make", "an", "absolute", "URLs", "to", "the", "given", "upload", "id", ".", "If", "the", "base", "path", "is", "absolute", "it", "will", "be", "prepended", "else", "the", "host", "and", "protocol", "from", "the", "request", "is", "used", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L798-L809
train
tus/tusd
unrouted_handler.go
sendProgressMessages
func (handler *UnroutedHandler) sendProgressMessages(info FileInfo, reader io.Reader) (io.Reader, chan<- struct{}) { progress := &progressWriter{ Offset: info.Offset, } stop := make(chan struct{}, 1) reader = io.TeeReader(reader, progress) go func() { for { select { case <-stop: info.Offset = atomic.LoadInt64(&progress.Offset) handler.UploadProgress <- info return case <-time.After(1 * time.Second): info.Offset = atomic.LoadInt64(&progress.Offset) handler.UploadProgress <- info } } }() return reader, stop }
go
func (handler *UnroutedHandler) sendProgressMessages(info FileInfo, reader io.Reader) (io.Reader, chan<- struct{}) { progress := &progressWriter{ Offset: info.Offset, } stop := make(chan struct{}, 1) reader = io.TeeReader(reader, progress) go func() { for { select { case <-stop: info.Offset = atomic.LoadInt64(&progress.Offset) handler.UploadProgress <- info return case <-time.After(1 * time.Second): info.Offset = atomic.LoadInt64(&progress.Offset) handler.UploadProgress <- info } } }() return reader, stop }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "sendProgressMessages", "(", "info", "FileInfo", ",", "reader", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "chan", "<-", "struct", "{", "}", ")", "{", "progress", ":=", "&", "progressWriter", "{", "Offset", ":", "info", ".", "Offset", ",", "}", "\n", "stop", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "reader", "=", "io", ".", "TeeReader", "(", "reader", ",", "progress", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "stop", ":", "info", ".", "Offset", "=", "atomic", ".", "LoadInt64", "(", "&", "progress", ".", "Offset", ")", "\n", "handler", ".", "UploadProgress", "<-", "info", "\n", "return", "\n", "case", "<-", "time", ".", "After", "(", "1", "*", "time", ".", "Second", ")", ":", "info", ".", "Offset", "=", "atomic", ".", "LoadInt64", "(", "&", "progress", ".", "Offset", ")", "\n", "handler", ".", "UploadProgress", "<-", "info", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "reader", ",", "stop", "\n", "}" ]
// sendProgressMessage will send a notification over the UploadProgress channel // every second, indicating how much data has been transfered to the server. // It will stop sending these instances once the returned channel has been // closed. The returned reader should be used to read the request body.
[ "sendProgressMessage", "will", "send", "a", "notification", "over", "the", "UploadProgress", "channel", "every", "second", "indicating", "how", "much", "data", "has", "been", "transfered", "to", "the", "server", ".", "It", "will", "stop", "sending", "these", "instances", "once", "the", "returned", "channel", "has", "been", "closed", ".", "The", "returned", "reader", "should", "be", "used", "to", "read", "the", "request", "body", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L824-L846
train
tus/tusd
unrouted_handler.go
sizeOfUploads
func (handler *UnroutedHandler) sizeOfUploads(ids []string) (size int64, err error) { for _, id := range ids { info, err := handler.composer.Core.GetInfo(id) if err != nil { return size, err } if info.SizeIsDeferred || info.Offset != info.Size { err = ErrUploadNotFinished return size, err } size += info.Size } return }
go
func (handler *UnroutedHandler) sizeOfUploads(ids []string) (size int64, err error) { for _, id := range ids { info, err := handler.composer.Core.GetInfo(id) if err != nil { return size, err } if info.SizeIsDeferred || info.Offset != info.Size { err = ErrUploadNotFinished return size, err } size += info.Size } return }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "sizeOfUploads", "(", "ids", "[", "]", "string", ")", "(", "size", "int64", ",", "err", "error", ")", "{", "for", "_", ",", "id", ":=", "range", "ids", "{", "info", ",", "err", ":=", "handler", ".", "composer", ".", "Core", ".", "GetInfo", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "size", ",", "err", "\n", "}", "\n", "if", "info", ".", "SizeIsDeferred", "||", "info", ".", "Offset", "!=", "info", ".", "Size", "{", "err", "=", "ErrUploadNotFinished", "\n", "return", "size", ",", "err", "\n", "}", "\n", "size", "+=", "info", ".", "Size", "\n", "}", "\n", "return", "\n", "}" ]
// The get sum of all sizes for a list of upload ids while checking whether // all of these uploads are finished yet. This is used to calculate the size // of a final resource.
[ "The", "get", "sum", "of", "all", "sizes", "for", "a", "list", "of", "upload", "ids", "while", "checking", "whether", "all", "of", "these", "uploads", "are", "finished", "yet", ".", "This", "is", "used", "to", "calculate", "the", "size", "of", "a", "final", "resource", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L889-L905
train
tus/tusd
unrouted_handler.go
validateNewUploadLengthHeaders
func (handler *UnroutedHandler) validateNewUploadLengthHeaders(uploadLengthHeader string, uploadDeferLengthHeader string) (uploadLength int64, uploadLengthDeferred bool, err error) { haveBothLengthHeaders := uploadLengthHeader != "" && uploadDeferLengthHeader != "" haveInvalidDeferHeader := uploadDeferLengthHeader != "" && uploadDeferLengthHeader != UploadLengthDeferred lengthIsDeferred := uploadDeferLengthHeader == UploadLengthDeferred if lengthIsDeferred && !handler.composer.UsesLengthDeferrer { err = ErrNotImplemented } else if haveBothLengthHeaders { err = ErrUploadLengthAndUploadDeferLength } else if haveInvalidDeferHeader { err = ErrInvalidUploadDeferLength } else if lengthIsDeferred { uploadLengthDeferred = true } else { uploadLength, err = strconv.ParseInt(uploadLengthHeader, 10, 64) if err != nil || uploadLength < 0 { err = ErrInvalidUploadLength } } return }
go
func (handler *UnroutedHandler) validateNewUploadLengthHeaders(uploadLengthHeader string, uploadDeferLengthHeader string) (uploadLength int64, uploadLengthDeferred bool, err error) { haveBothLengthHeaders := uploadLengthHeader != "" && uploadDeferLengthHeader != "" haveInvalidDeferHeader := uploadDeferLengthHeader != "" && uploadDeferLengthHeader != UploadLengthDeferred lengthIsDeferred := uploadDeferLengthHeader == UploadLengthDeferred if lengthIsDeferred && !handler.composer.UsesLengthDeferrer { err = ErrNotImplemented } else if haveBothLengthHeaders { err = ErrUploadLengthAndUploadDeferLength } else if haveInvalidDeferHeader { err = ErrInvalidUploadDeferLength } else if lengthIsDeferred { uploadLengthDeferred = true } else { uploadLength, err = strconv.ParseInt(uploadLengthHeader, 10, 64) if err != nil || uploadLength < 0 { err = ErrInvalidUploadLength } } return }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "validateNewUploadLengthHeaders", "(", "uploadLengthHeader", "string", ",", "uploadDeferLengthHeader", "string", ")", "(", "uploadLength", "int64", ",", "uploadLengthDeferred", "bool", ",", "err", "error", ")", "{", "haveBothLengthHeaders", ":=", "uploadLengthHeader", "!=", "\"\"", "&&", "uploadDeferLengthHeader", "!=", "\"\"", "\n", "haveInvalidDeferHeader", ":=", "uploadDeferLengthHeader", "!=", "\"\"", "&&", "uploadDeferLengthHeader", "!=", "UploadLengthDeferred", "\n", "lengthIsDeferred", ":=", "uploadDeferLengthHeader", "==", "UploadLengthDeferred", "\n", "if", "lengthIsDeferred", "&&", "!", "handler", ".", "composer", ".", "UsesLengthDeferrer", "{", "err", "=", "ErrNotImplemented", "\n", "}", "else", "if", "haveBothLengthHeaders", "{", "err", "=", "ErrUploadLengthAndUploadDeferLength", "\n", "}", "else", "if", "haveInvalidDeferHeader", "{", "err", "=", "ErrInvalidUploadDeferLength", "\n", "}", "else", "if", "lengthIsDeferred", "{", "uploadLengthDeferred", "=", "true", "\n", "}", "else", "{", "uploadLength", ",", "err", "=", "strconv", ".", "ParseInt", "(", "uploadLengthHeader", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "||", "uploadLength", "<", "0", "{", "err", "=", "ErrInvalidUploadLength", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Verify that the Upload-Length and Upload-Defer-Length headers are acceptable for creating a // new upload
[ "Verify", "that", "the", "Upload", "-", "Length", "and", "Upload", "-", "Defer", "-", "Length", "headers", "are", "acceptable", "for", "creating", "a", "new", "upload" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L909-L930
train
tus/tusd
unrouted_handler.go
extractIDFromPath
func extractIDFromPath(url string) (string, error) { result := reExtractFileID.FindStringSubmatch(url) if len(result) != 2 { return "", ErrNotFound } return result[1], nil }
go
func extractIDFromPath(url string) (string, error) { result := reExtractFileID.FindStringSubmatch(url) if len(result) != 2 { return "", ErrNotFound } return result[1], nil }
[ "func", "extractIDFromPath", "(", "url", "string", ")", "(", "string", ",", "error", ")", "{", "result", ":=", "reExtractFileID", ".", "FindStringSubmatch", "(", "url", ")", "\n", "if", "len", "(", "result", ")", "!=", "2", "{", "return", "\"\"", ",", "ErrNotFound", "\n", "}", "\n", "return", "result", "[", "1", "]", ",", "nil", "\n", "}" ]
// extractIDFromPath pulls the last segment from the url provided
[ "extractIDFromPath", "pulls", "the", "last", "segment", "from", "the", "url", "provided" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L1023-L1029
train
tus/tusd
gcsstore/gcsservice.go
NewGCSService
func NewGCSService(filename string) (*GCSService, error) { ctx := context.Background() client, err := storage.NewClient(ctx, option.WithServiceAccountFile(filename)) if err != nil { return nil, err } service := &GCSService{ Client: client, } return service, nil }
go
func NewGCSService(filename string) (*GCSService, error) { ctx := context.Background() client, err := storage.NewClient(ctx, option.WithServiceAccountFile(filename)) if err != nil { return nil, err } service := &GCSService{ Client: client, } return service, nil }
[ "func", "NewGCSService", "(", "filename", "string", ")", "(", "*", "GCSService", ",", "error", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "client", ",", "err", ":=", "storage", ".", "NewClient", "(", "ctx", ",", "option", ".", "WithServiceAccountFile", "(", "filename", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "service", ":=", "&", "GCSService", "{", "Client", ":", "client", ",", "}", "\n", "return", "service", ",", "nil", "\n", "}" ]
// NewGCSService returns a GCSSerivce object given a GCloud service account file path.
[ "NewGCSService", "returns", "a", "GCSSerivce", "object", "given", "a", "GCloud", "service", "account", "file", "path", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L82-L94
train
tus/tusd
gcsstore/gcsservice.go
GetObjectSize
func (service *GCSService) GetObjectSize(ctx context.Context, params GCSObjectParams) (int64, error) { attrs, err := service.GetObjectAttrs(ctx, params) if err != nil { return 0, err } return attrs.Size, nil }
go
func (service *GCSService) GetObjectSize(ctx context.Context, params GCSObjectParams) (int64, error) { attrs, err := service.GetObjectAttrs(ctx, params) if err != nil { return 0, err } return attrs.Size, nil }
[ "func", "(", "service", "*", "GCSService", ")", "GetObjectSize", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ")", "(", "int64", ",", "error", ")", "{", "attrs", ",", "err", ":=", "service", ".", "GetObjectAttrs", "(", "ctx", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "attrs", ".", "Size", ",", "nil", "\n", "}" ]
// GetObjectSize returns the byte length of the specified GCS object.
[ "GetObjectSize", "returns", "the", "byte", "length", "of", "the", "specified", "GCS", "object", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L97-L104
train
tus/tusd
gcsstore/gcsservice.go
DeleteObjectsWithFilter
func (service *GCSService) DeleteObjectsWithFilter(ctx context.Context, params GCSFilterParams) error { names, err := service.FilterObjects(ctx, params) if err != nil { return err } var objectParams GCSObjectParams for _, name := range names { objectParams = GCSObjectParams{ Bucket: params.Bucket, ID: name, } err := service.DeleteObject(ctx, objectParams) if err != nil { return err } } return nil }
go
func (service *GCSService) DeleteObjectsWithFilter(ctx context.Context, params GCSFilterParams) error { names, err := service.FilterObjects(ctx, params) if err != nil { return err } var objectParams GCSObjectParams for _, name := range names { objectParams = GCSObjectParams{ Bucket: params.Bucket, ID: name, } err := service.DeleteObject(ctx, objectParams) if err != nil { return err } } return nil }
[ "func", "(", "service", "*", "GCSService", ")", "DeleteObjectsWithFilter", "(", "ctx", "context", ".", "Context", ",", "params", "GCSFilterParams", ")", "error", "{", "names", ",", "err", ":=", "service", ".", "FilterObjects", "(", "ctx", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "objectParams", "GCSObjectParams", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "objectParams", "=", "GCSObjectParams", "{", "Bucket", ":", "params", ".", "Bucket", ",", "ID", ":", "name", ",", "}", "\n", "err", ":=", "service", ".", "DeleteObject", "(", "ctx", ",", "objectParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteObjectWithPrefix will delete objects who match the provided filter parameters.
[ "DeleteObjectWithPrefix", "will", "delete", "objects", "who", "match", "the", "provided", "filter", "parameters", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L107-L127
train
tus/tusd
gcsstore/gcsservice.go
compose
func (service *GCSService) compose(ctx context.Context, bucket string, srcs []string, dst string) error { dstParams := GCSObjectParams{ Bucket: bucket, ID: dst, } objSrcs := make([]*storage.ObjectHandle, len(srcs)) var crc uint32 for i := 0; i < len(srcs); i++ { objSrcs[i] = service.Client.Bucket(bucket).Object(srcs[i]) srcAttrs, err := service.GetObjectAttrs(ctx, GCSObjectParams{ Bucket: bucket, ID: srcs[i], }) if err != nil { return err } if i == 0 { crc = srcAttrs.CRC32C } else { crc = crc32combine.CRC32Combine(crc32.Castagnoli, crc, srcAttrs.CRC32C, srcAttrs.Size) } } attrs, err := service.GetObjectAttrs(ctx, GCSObjectParams{ Bucket: bucket, ID: srcs[0], }) if err != nil { return err } for i := 0; i < COMPOSE_RETRIES; i++ { dstCRC, err := service.ComposeFrom(ctx, objSrcs, dstParams, attrs.ContentType) if err != nil { return err } if dstCRC == crc { return nil } } err = service.DeleteObject(ctx, GCSObjectParams{ Bucket: bucket, ID: dst, }) if err != nil { return err } err = errors.New("GCS compose failed: Mismatch of CRC32 checksums") return err }
go
func (service *GCSService) compose(ctx context.Context, bucket string, srcs []string, dst string) error { dstParams := GCSObjectParams{ Bucket: bucket, ID: dst, } objSrcs := make([]*storage.ObjectHandle, len(srcs)) var crc uint32 for i := 0; i < len(srcs); i++ { objSrcs[i] = service.Client.Bucket(bucket).Object(srcs[i]) srcAttrs, err := service.GetObjectAttrs(ctx, GCSObjectParams{ Bucket: bucket, ID: srcs[i], }) if err != nil { return err } if i == 0 { crc = srcAttrs.CRC32C } else { crc = crc32combine.CRC32Combine(crc32.Castagnoli, crc, srcAttrs.CRC32C, srcAttrs.Size) } } attrs, err := service.GetObjectAttrs(ctx, GCSObjectParams{ Bucket: bucket, ID: srcs[0], }) if err != nil { return err } for i := 0; i < COMPOSE_RETRIES; i++ { dstCRC, err := service.ComposeFrom(ctx, objSrcs, dstParams, attrs.ContentType) if err != nil { return err } if dstCRC == crc { return nil } } err = service.DeleteObject(ctx, GCSObjectParams{ Bucket: bucket, ID: dst, }) if err != nil { return err } err = errors.New("GCS compose failed: Mismatch of CRC32 checksums") return err }
[ "func", "(", "service", "*", "GCSService", ")", "compose", "(", "ctx", "context", ".", "Context", ",", "bucket", "string", ",", "srcs", "[", "]", "string", ",", "dst", "string", ")", "error", "{", "dstParams", ":=", "GCSObjectParams", "{", "Bucket", ":", "bucket", ",", "ID", ":", "dst", ",", "}", "\n", "objSrcs", ":=", "make", "(", "[", "]", "*", "storage", ".", "ObjectHandle", ",", "len", "(", "srcs", ")", ")", "\n", "var", "crc", "uint32", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "srcs", ")", ";", "i", "++", "{", "objSrcs", "[", "i", "]", "=", "service", ".", "Client", ".", "Bucket", "(", "bucket", ")", ".", "Object", "(", "srcs", "[", "i", "]", ")", "\n", "srcAttrs", ",", "err", ":=", "service", ".", "GetObjectAttrs", "(", "ctx", ",", "GCSObjectParams", "{", "Bucket", ":", "bucket", ",", "ID", ":", "srcs", "[", "i", "]", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "i", "==", "0", "{", "crc", "=", "srcAttrs", ".", "CRC32C", "\n", "}", "else", "{", "crc", "=", "crc32combine", ".", "CRC32Combine", "(", "crc32", ".", "Castagnoli", ",", "crc", ",", "srcAttrs", ".", "CRC32C", ",", "srcAttrs", ".", "Size", ")", "\n", "}", "\n", "}", "\n", "attrs", ",", "err", ":=", "service", ".", "GetObjectAttrs", "(", "ctx", ",", "GCSObjectParams", "{", "Bucket", ":", "bucket", ",", "ID", ":", "srcs", "[", "0", "]", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "COMPOSE_RETRIES", ";", "i", "++", "{", "dstCRC", ",", "err", ":=", "service", ".", "ComposeFrom", "(", "ctx", ",", "objSrcs", ",", "dstParams", ",", "attrs", ".", "ContentType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "dstCRC", "==", "crc", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "err", "=", "service", ".", "DeleteObject", "(", "ctx", ",", "GCSObjectParams", "{", "Bucket", ":", "bucket", ",", "ID", ":", "dst", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "errors", ".", "New", "(", "\"GCS compose failed: Mismatch of CRC32 checksums\"", ")", "\n", "return", "err", "\n", "}" ]
// Compose takes a bucket name, a list of initial source names, and a destination string to compose multiple GCS objects together
[ "Compose", "takes", "a", "bucket", "name", "a", "list", "of", "initial", "source", "names", "and", "a", "destination", "string", "to", "compose", "multiple", "GCS", "objects", "together" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L132-L186
train
tus/tusd
gcsstore/gcsservice.go
ComposeObjects
func (service *GCSService) ComposeObjects(ctx context.Context, params GCSComposeParams) error { err := service.recursiveCompose(ctx, params.Sources, params, 0) if err != nil { return err } return nil }
go
func (service *GCSService) ComposeObjects(ctx context.Context, params GCSComposeParams) error { err := service.recursiveCompose(ctx, params.Sources, params, 0) if err != nil { return err } return nil }
[ "func", "(", "service", "*", "GCSService", ")", "ComposeObjects", "(", "ctx", "context", ".", "Context", ",", "params", "GCSComposeParams", ")", "error", "{", "err", ":=", "service", ".", "recursiveCompose", "(", "ctx", ",", "params", ".", "Sources", ",", "params", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ComposeObjects composes multiple GCS objects in to a single object. // Since GCS limits composition to a max of 32 objects, additional logic // has been added to chunk objects in to groups of 32 and then recursively // compose those objects together.
[ "ComposeObjects", "composes", "multiple", "GCS", "objects", "in", "to", "a", "single", "object", ".", "Since", "GCS", "limits", "composition", "to", "a", "max", "of", "32", "objects", "additional", "logic", "has", "been", "added", "to", "chunk", "objects", "in", "to", "groups", "of", "32", "and", "then", "recursively", "compose", "those", "objects", "together", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L240-L248
train
tus/tusd
gcsstore/gcsservice.go
ReadObject
func (service *GCSService) ReadObject(ctx context.Context, params GCSObjectParams) (GCSReader, error) { r, err := service.Client.Bucket(params.Bucket).Object(params.ID).NewReader(ctx) if err != nil { return nil, err } return r, nil }
go
func (service *GCSService) ReadObject(ctx context.Context, params GCSObjectParams) (GCSReader, error) { r, err := service.Client.Bucket(params.Bucket).Object(params.ID).NewReader(ctx) if err != nil { return nil, err } return r, nil }
[ "func", "(", "service", "*", "GCSService", ")", "ReadObject", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ")", "(", "GCSReader", ",", "error", ")", "{", "r", ",", "err", ":=", "service", ".", "Client", ".", "Bucket", "(", "params", ".", "Bucket", ")", ".", "Object", "(", "params", ".", "ID", ")", ".", "NewReader", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// ReadObject reads a GCSObjectParams, returning a GCSReader object if successful, and an error otherwise
[ "ReadObject", "reads", "a", "GCSObjectParams", "returning", "a", "GCSReader", "object", "if", "successful", "and", "an", "error", "otherwise" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L264-L271
train
tus/tusd
gcsstore/gcsservice.go
SetObjectMetadata
func (service *GCSService) SetObjectMetadata(ctx context.Context, params GCSObjectParams, metadata map[string]string) error { attrs := storage.ObjectAttrsToUpdate{ Metadata: metadata, } _, err := service.Client.Bucket(params.Bucket).Object(params.ID).Update(ctx, attrs) return err }
go
func (service *GCSService) SetObjectMetadata(ctx context.Context, params GCSObjectParams, metadata map[string]string) error { attrs := storage.ObjectAttrsToUpdate{ Metadata: metadata, } _, err := service.Client.Bucket(params.Bucket).Object(params.ID).Update(ctx, attrs) return err }
[ "func", "(", "service", "*", "GCSService", ")", "SetObjectMetadata", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ",", "metadata", "map", "[", "string", "]", "string", ")", "error", "{", "attrs", ":=", "storage", ".", "ObjectAttrsToUpdate", "{", "Metadata", ":", "metadata", ",", "}", "\n", "_", ",", "err", ":=", "service", ".", "Client", ".", "Bucket", "(", "params", ".", "Bucket", ")", ".", "Object", "(", "params", ".", "ID", ")", ".", "Update", "(", "ctx", ",", "attrs", ")", "\n", "return", "err", "\n", "}" ]
// SetObjectMetadata reads a GCSObjectParams and a map of metedata, returning a nil on sucess and an error otherwise
[ "SetObjectMetadata", "reads", "a", "GCSObjectParams", "and", "a", "map", "of", "metedata", "returning", "a", "nil", "on", "sucess", "and", "an", "error", "otherwise" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L274-L281
train
tus/tusd
gcsstore/gcsservice.go
DeleteObject
func (service *GCSService) DeleteObject(ctx context.Context, params GCSObjectParams) error { return service.Client.Bucket(params.Bucket).Object(params.ID).Delete(ctx) }
go
func (service *GCSService) DeleteObject(ctx context.Context, params GCSObjectParams) error { return service.Client.Bucket(params.Bucket).Object(params.ID).Delete(ctx) }
[ "func", "(", "service", "*", "GCSService", ")", "DeleteObject", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ")", "error", "{", "return", "service", ".", "Client", ".", "Bucket", "(", "params", ".", "Bucket", ")", ".", "Object", "(", "params", ".", "ID", ")", ".", "Delete", "(", "ctx", ")", "\n", "}" ]
// DeleteObject deletes the object defined by GCSObjectParams
[ "DeleteObject", "deletes", "the", "object", "defined", "by", "GCSObjectParams" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L284-L286
train
tus/tusd
gcsstore/gcsservice.go
WriteObject
func (service *GCSService) WriteObject(ctx context.Context, params GCSObjectParams, r io.Reader) (int64, error) { obj := service.Client.Bucket(params.Bucket).Object(params.ID) w := obj.NewWriter(ctx) n, err := io.Copy(w, r) if err != nil { return 0, err } err = w.Close() if err != nil { if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == 404 { return 0, fmt.Errorf("gcsstore: the bucket %s could not be found while trying to write an object", params.Bucket) } return 0, err } return n, err }
go
func (service *GCSService) WriteObject(ctx context.Context, params GCSObjectParams, r io.Reader) (int64, error) { obj := service.Client.Bucket(params.Bucket).Object(params.ID) w := obj.NewWriter(ctx) n, err := io.Copy(w, r) if err != nil { return 0, err } err = w.Close() if err != nil { if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == 404 { return 0, fmt.Errorf("gcsstore: the bucket %s could not be found while trying to write an object", params.Bucket) } return 0, err } return n, err }
[ "func", "(", "service", "*", "GCSService", ")", "WriteObject", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ",", "r", "io", ".", "Reader", ")", "(", "int64", ",", "error", ")", "{", "obj", ":=", "service", ".", "Client", ".", "Bucket", "(", "params", ".", "Bucket", ")", ".", "Object", "(", "params", ".", "ID", ")", "\n", "w", ":=", "obj", ".", "NewWriter", "(", "ctx", ")", "\n", "n", ",", "err", ":=", "io", ".", "Copy", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "err", "=", "w", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "gErr", ",", "ok", ":=", "err", ".", "(", "*", "googleapi", ".", "Error", ")", ";", "ok", "&&", "gErr", ".", "Code", "==", "404", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"gcsstore: the bucket %s could not be found while trying to write an object\"", ",", "params", ".", "Bucket", ")", "\n", "}", "\n", "return", "0", ",", "err", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Write object writes the file set out by the GCSObjectParams
[ "Write", "object", "writes", "the", "file", "set", "out", "by", "the", "GCSObjectParams" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L289-L308
train
tus/tusd
gcsstore/gcsservice.go
ComposeFrom
func (service *GCSService) ComposeFrom(ctx context.Context, objSrcs []*storage.ObjectHandle, dstParams GCSObjectParams, contentType string) (uint32, error) { dstObj := service.Client.Bucket(dstParams.Bucket).Object(dstParams.ID) c := dstObj.ComposerFrom(objSrcs...) c.ContentType = contentType _, err := c.Run(ctx) if err != nil { return 0, err } dstAttrs, err := dstObj.Attrs(ctx) if err != nil { return 0, err } return dstAttrs.CRC32C, nil }
go
func (service *GCSService) ComposeFrom(ctx context.Context, objSrcs []*storage.ObjectHandle, dstParams GCSObjectParams, contentType string) (uint32, error) { dstObj := service.Client.Bucket(dstParams.Bucket).Object(dstParams.ID) c := dstObj.ComposerFrom(objSrcs...) c.ContentType = contentType _, err := c.Run(ctx) if err != nil { return 0, err } dstAttrs, err := dstObj.Attrs(ctx) if err != nil { return 0, err } return dstAttrs.CRC32C, nil }
[ "func", "(", "service", "*", "GCSService", ")", "ComposeFrom", "(", "ctx", "context", ".", "Context", ",", "objSrcs", "[", "]", "*", "storage", ".", "ObjectHandle", ",", "dstParams", "GCSObjectParams", ",", "contentType", "string", ")", "(", "uint32", ",", "error", ")", "{", "dstObj", ":=", "service", ".", "Client", ".", "Bucket", "(", "dstParams", ".", "Bucket", ")", ".", "Object", "(", "dstParams", ".", "ID", ")", "\n", "c", ":=", "dstObj", ".", "ComposerFrom", "(", "objSrcs", "...", ")", "\n", "c", ".", "ContentType", "=", "contentType", "\n", "_", ",", "err", ":=", "c", ".", "Run", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "dstAttrs", ",", "err", ":=", "dstObj", ".", "Attrs", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "dstAttrs", ".", "CRC32C", ",", "nil", "\n", "}" ]
// ComposeFrom composes multiple object types together,
[ "ComposeFrom", "composes", "multiple", "object", "types", "together" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L311-L326
train
tus/tusd
memorylocker/memorylocker.go
UnlockUpload
func (locker *MemoryLocker) UnlockUpload(id string) error { locker.mutex.Lock() // Deleting a non-existing key does not end in unexpected errors or panic // since this operation results in a no-op delete(locker.locks, id) locker.mutex.Unlock() return nil }
go
func (locker *MemoryLocker) UnlockUpload(id string) error { locker.mutex.Lock() // Deleting a non-existing key does not end in unexpected errors or panic // since this operation results in a no-op delete(locker.locks, id) locker.mutex.Unlock() return nil }
[ "func", "(", "locker", "*", "MemoryLocker", ")", "UnlockUpload", "(", "id", "string", ")", "error", "{", "locker", ".", "mutex", ".", "Lock", "(", ")", "\n", "delete", "(", "locker", ".", "locks", ",", "id", ")", "\n", "locker", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// UnlockUpload releases a lock. If no such lock exists, no error will be returned.
[ "UnlockUpload", "releases", "a", "lock", ".", "If", "no", "such", "lock", "exists", "no", "error", "will", "be", "returned", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/memorylocker/memorylocker.go#L62-L71
train
tus/tusd
gcsstore/gcsstore.go
New
func New(bucket string, service GCSAPI) GCSStore { return GCSStore{ Bucket: bucket, Service: service, } }
go
func New(bucket string, service GCSAPI) GCSStore { return GCSStore{ Bucket: bucket, Service: service, } }
[ "func", "New", "(", "bucket", "string", ",", "service", "GCSAPI", ")", "GCSStore", "{", "return", "GCSStore", "{", "Bucket", ":", "bucket", ",", "Service", ":", "service", ",", "}", "\n", "}" ]
// New constructs a new GCS storage backend using the supplied GCS bucket name // and service object.
[ "New", "constructs", "a", "new", "GCS", "storage", "backend", "using", "the", "supplied", "GCS", "bucket", "name", "and", "service", "object", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsstore.go#L42-L47
train
tus/tusd
etcd3locker/locker.go
NewWithPrefix
func NewWithPrefix(client *etcd3.Client, prefix string) (*Etcd3Locker, error) { lockerOptions := DefaultLockerOptions() lockerOptions.SetPrefix(prefix) return NewWithLockerOptions(client, lockerOptions) }
go
func NewWithPrefix(client *etcd3.Client, prefix string) (*Etcd3Locker, error) { lockerOptions := DefaultLockerOptions() lockerOptions.SetPrefix(prefix) return NewWithLockerOptions(client, lockerOptions) }
[ "func", "NewWithPrefix", "(", "client", "*", "etcd3", ".", "Client", ",", "prefix", "string", ")", "(", "*", "Etcd3Locker", ",", "error", ")", "{", "lockerOptions", ":=", "DefaultLockerOptions", "(", ")", "\n", "lockerOptions", ".", "SetPrefix", "(", "prefix", ")", "\n", "return", "NewWithLockerOptions", "(", "client", ",", "lockerOptions", ")", "\n", "}" ]
// This method may be used if a different prefix is required for multi-tenant etcd clusters
[ "This", "method", "may", "be", "used", "if", "a", "different", "prefix", "is", "required", "for", "multi", "-", "tenant", "etcd", "clusters" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/etcd3locker/locker.go#L79-L83
train
tus/tusd
composer.go
newStoreComposerFromDataStore
func newStoreComposerFromDataStore(store DataStore) *StoreComposer { composer := NewStoreComposer() composer.UseCore(store) if mod, ok := store.(TerminaterDataStore); ok { composer.UseTerminater(mod) } if mod, ok := store.(FinisherDataStore); ok { composer.UseFinisher(mod) } if mod, ok := store.(LockerDataStore); ok { composer.UseLocker(mod) } if mod, ok := store.(GetReaderDataStore); ok { composer.UseGetReader(mod) } if mod, ok := store.(ConcaterDataStore); ok { composer.UseConcater(mod) } if mod, ok := store.(LengthDeferrerDataStore); ok { composer.UseLengthDeferrer(mod) } return composer }
go
func newStoreComposerFromDataStore(store DataStore) *StoreComposer { composer := NewStoreComposer() composer.UseCore(store) if mod, ok := store.(TerminaterDataStore); ok { composer.UseTerminater(mod) } if mod, ok := store.(FinisherDataStore); ok { composer.UseFinisher(mod) } if mod, ok := store.(LockerDataStore); ok { composer.UseLocker(mod) } if mod, ok := store.(GetReaderDataStore); ok { composer.UseGetReader(mod) } if mod, ok := store.(ConcaterDataStore); ok { composer.UseConcater(mod) } if mod, ok := store.(LengthDeferrerDataStore); ok { composer.UseLengthDeferrer(mod) } return composer }
[ "func", "newStoreComposerFromDataStore", "(", "store", "DataStore", ")", "*", "StoreComposer", "{", "composer", ":=", "NewStoreComposer", "(", ")", "\n", "composer", ".", "UseCore", "(", "store", ")", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "TerminaterDataStore", ")", ";", "ok", "{", "composer", ".", "UseTerminater", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "FinisherDataStore", ")", ";", "ok", "{", "composer", ".", "UseFinisher", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "LockerDataStore", ")", ";", "ok", "{", "composer", ".", "UseLocker", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "GetReaderDataStore", ")", ";", "ok", "{", "composer", ".", "UseGetReader", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "ConcaterDataStore", ")", ";", "ok", "{", "composer", ".", "UseConcater", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "LengthDeferrerDataStore", ")", ";", "ok", "{", "composer", ".", "UseLengthDeferrer", "(", "mod", ")", "\n", "}", "\n", "return", "composer", "\n", "}" ]
// newStoreComposerFromDataStore creates a new store composer and attempts to // extract the extensions for the provided store. This is intended to be used // for transitioning from data stores to composers.
[ "newStoreComposerFromDataStore", "creates", "a", "new", "store", "composer", "and", "attempts", "to", "extract", "the", "extensions", "for", "the", "provided", "store", ".", "This", "is", "intended", "to", "be", "used", "for", "transitioning", "from", "data", "stores", "to", "composers", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/composer.go#L31-L55
train
tus/tusd
composer.go
Capabilities
func (store *StoreComposer) Capabilities() string { str := "Core: " if store.Core != nil { str += "βœ“" } else { str += "βœ—" } str += ` Terminater: ` if store.UsesTerminater { str += "βœ“" } else { str += "βœ—" } str += ` Finisher: ` if store.UsesFinisher { str += "βœ“" } else { str += "βœ—" } str += ` Locker: ` if store.UsesLocker { str += "βœ“" } else { str += "βœ—" } str += ` GetReader: ` if store.UsesGetReader { str += "βœ“" } else { str += "βœ—" } str += ` Concater: ` if store.UsesConcater { str += "βœ“" } else { str += "βœ—" } str += ` LengthDeferrer: ` if store.UsesLengthDeferrer { str += "βœ“" } else { str += "βœ—" } return str }
go
func (store *StoreComposer) Capabilities() string { str := "Core: " if store.Core != nil { str += "βœ“" } else { str += "βœ—" } str += ` Terminater: ` if store.UsesTerminater { str += "βœ“" } else { str += "βœ—" } str += ` Finisher: ` if store.UsesFinisher { str += "βœ“" } else { str += "βœ—" } str += ` Locker: ` if store.UsesLocker { str += "βœ“" } else { str += "βœ—" } str += ` GetReader: ` if store.UsesGetReader { str += "βœ“" } else { str += "βœ—" } str += ` Concater: ` if store.UsesConcater { str += "βœ“" } else { str += "βœ—" } str += ` LengthDeferrer: ` if store.UsesLengthDeferrer { str += "βœ“" } else { str += "βœ—" } return str }
[ "func", "(", "store", "*", "StoreComposer", ")", "Capabilities", "(", ")", "string", "{", "str", ":=", "\"Core: \"", "\n", "if", "store", ".", "Core", "!=", "nil", "{", "str", "+=", "\"βœ“\"", "\n", "}", "else", "{", "str", "+=", "\"βœ—\"", "\n", "}", "\n", "str", "+=", "` Terminater: `", "\n", "if", "store", ".", "UsesTerminater", "{", "str", "+=", "\"βœ“\"", "\n", "}", "else", "{", "str", "+=", "\"βœ—\"", "\n", "}", "\n", "str", "+=", "` Finisher: `", "\n", "if", "store", ".", "UsesFinisher", "{", "str", "+=", "\"βœ“\"", "\n", "}", "else", "{", "str", "+=", "\"βœ—\"", "\n", "}", "\n", "str", "+=", "` Locker: `", "\n", "if", "store", ".", "UsesLocker", "{", "str", "+=", "\"βœ“\"", "\n", "}", "else", "{", "str", "+=", "\"βœ—\"", "\n", "}", "\n", "str", "+=", "` GetReader: `", "\n", "if", "store", ".", "UsesGetReader", "{", "str", "+=", "\"βœ“\"", "\n", "}", "else", "{", "str", "+=", "\"βœ—\"", "\n", "}", "\n", "str", "+=", "` Concater: `", "\n", "if", "store", ".", "UsesConcater", "{", "str", "+=", "\"βœ“\"", "\n", "}", "else", "{", "str", "+=", "\"βœ—\"", "\n", "}", "\n", "str", "+=", "` LengthDeferrer: `", "\n", "if", "store", ".", "UsesLengthDeferrer", "{", "str", "+=", "\"βœ“\"", "\n", "}", "else", "{", "str", "+=", "\"βœ—\"", "\n", "}", "\n", "return", "str", "\n", "}" ]
// Capabilities returns a string representing the provided extensions in a // human-readable format meant for debugging.
[ "Capabilities", "returns", "a", "string", "representing", "the", "provided", "extensions", "in", "a", "human", "-", "readable", "format", "meant", "for", "debugging", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/composer.go#L59-L106
train
tus/tusd
s3store/s3store.go
New
func New(bucket string, service S3API) S3Store { return S3Store{ Bucket: bucket, Service: service, MaxPartSize: 5 * 1024 * 1024 * 1024, MinPartSize: 5 * 1024 * 1024, MaxMultipartParts: 10000, MaxObjectSize: 5 * 1024 * 1024 * 1024 * 1024, } }
go
func New(bucket string, service S3API) S3Store { return S3Store{ Bucket: bucket, Service: service, MaxPartSize: 5 * 1024 * 1024 * 1024, MinPartSize: 5 * 1024 * 1024, MaxMultipartParts: 10000, MaxObjectSize: 5 * 1024 * 1024 * 1024 * 1024, } }
[ "func", "New", "(", "bucket", "string", ",", "service", "S3API", ")", "S3Store", "{", "return", "S3Store", "{", "Bucket", ":", "bucket", ",", "Service", ":", "service", ",", "MaxPartSize", ":", "5", "*", "1024", "*", "1024", "*", "1024", ",", "MinPartSize", ":", "5", "*", "1024", "*", "1024", ",", "MaxMultipartParts", ":", "10000", ",", "MaxObjectSize", ":", "5", "*", "1024", "*", "1024", "*", "1024", "*", "1024", ",", "}", "\n", "}" ]
// New constructs a new storage using the supplied bucket and service object.
[ "New", "constructs", "a", "new", "storage", "using", "the", "supplied", "bucket", "and", "service", "object", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/s3store/s3store.go#L147-L156
train
tus/tusd
s3store/s3store.go
isAwsError
func isAwsError(err error, code string) bool { if err, ok := err.(awserr.Error); ok && err.Code() == code { return true } return false }
go
func isAwsError(err error, code string) bool { if err, ok := err.(awserr.Error); ok && err.Code() == code { return true } return false }
[ "func", "isAwsError", "(", "err", "error", ",", "code", "string", ")", "bool", "{", "if", "err", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "&&", "err", ".", "Code", "(", ")", "==", "code", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isAwsError tests whether an error object is an instance of the AWS error // specified by its code.
[ "isAwsError", "tests", "whether", "an", "error", "object", "is", "an", "instance", "of", "the", "AWS", "error", "specified", "by", "its", "code", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/s3store/s3store.go#L676-L681
train