repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
tealeg/xlsx
lib.go
calculateMaxMinFromWorksheet
func calculateMaxMinFromWorksheet(worksheet *xlsxWorksheet) (minx, miny, maxx, maxy int, err error) { // Note, this method could be very slow for large spreadsheets. var x, y int var maxVal int maxVal = int(^uint(0) >> 1) minx = maxVal miny = maxVal maxy = 0 maxx = 0 for _, row := range worksheet.SheetData.Row { for _, cell := range row.C { x, y, err = GetCoordsFromCellIDString(cell.R) if err != nil { return -1, -1, -1, -1, err } if x < minx { minx = x } if x > maxx { maxx = x } if y < miny { miny = y } if y > maxy { maxy = y } } } if minx == maxVal { minx = 0 } if miny == maxVal { miny = 0 } return }
go
func calculateMaxMinFromWorksheet(worksheet *xlsxWorksheet) (minx, miny, maxx, maxy int, err error) { // Note, this method could be very slow for large spreadsheets. var x, y int var maxVal int maxVal = int(^uint(0) >> 1) minx = maxVal miny = maxVal maxy = 0 maxx = 0 for _, row := range worksheet.SheetData.Row { for _, cell := range row.C { x, y, err = GetCoordsFromCellIDString(cell.R) if err != nil { return -1, -1, -1, -1, err } if x < minx { minx = x } if x > maxx { maxx = x } if y < miny { miny = y } if y > maxy { maxy = y } } } if minx == maxVal { minx = 0 } if miny == maxVal { miny = 0 } return }
[ "func", "calculateMaxMinFromWorksheet", "(", "worksheet", "*", "xlsxWorksheet", ")", "(", "minx", ",", "miny", ",", "maxx", ",", "maxy", "int", ",", "err", "error", ")", "{", "// Note, this method could be very slow for large spreadsheets.", "var", "x", ",", "y", "int", "\n", "var", "maxVal", "int", "\n", "maxVal", "=", "int", "(", "^", "uint", "(", "0", ")", ">>", "1", ")", "\n", "minx", "=", "maxVal", "\n", "miny", "=", "maxVal", "\n", "maxy", "=", "0", "\n", "maxx", "=", "0", "\n", "for", "_", ",", "row", ":=", "range", "worksheet", ".", "SheetData", ".", "Row", "{", "for", "_", ",", "cell", ":=", "range", "row", ".", "C", "{", "x", ",", "y", ",", "err", "=", "GetCoordsFromCellIDString", "(", "cell", ".", "R", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "-", "1", ",", "-", "1", ",", "-", "1", ",", "err", "\n", "}", "\n", "if", "x", "<", "minx", "{", "minx", "=", "x", "\n", "}", "\n", "if", "x", ">", "maxx", "{", "maxx", "=", "x", "\n", "}", "\n", "if", "y", "<", "miny", "{", "miny", "=", "y", "\n", "}", "\n", "if", "y", ">", "maxy", "{", "maxy", "=", "y", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "minx", "==", "maxVal", "{", "minx", "=", "0", "\n", "}", "\n", "if", "miny", "==", "maxVal", "{", "miny", "=", "0", "\n", "}", "\n", "return", "\n", "}" ]
// calculateMaxMinFromWorkSheet works out the dimensions of a spreadsheet // that doesn't have a DimensionRef set. The only case currently // known where this is true is with XLSX exported from Google Docs. // This is also true for XLSX files created through the streaming APIs.
[ "calculateMaxMinFromWorkSheet", "works", "out", "the", "dimensions", "of", "a", "spreadsheet", "that", "doesn", "t", "have", "a", "DimensionRef", "set", ".", "The", "only", "case", "currently", "known", "where", "this", "is", "true", "is", "with", "XLSX", "exported", "from", "Google", "Docs", ".", "This", "is", "also", "true", "for", "XLSX", "files", "created", "through", "the", "streaming", "APIs", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L236-L272
train
tealeg/xlsx
lib.go
makeRowFromRaw
func makeRowFromRaw(rawrow xlsxRow, sheet *Sheet) *Row { var upper int var row *Row var cell *Cell row = new(Row) row.Sheet = sheet upper = -1 for _, rawcell := range rawrow.C { if rawcell.R != "" { x, _, error := GetCoordsFromCellIDString(rawcell.R) if error != nil { panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R)) } if x > upper { upper = x } continue } upper++ } upper++ row.OutlineLevel = rawrow.OutlineLevel row.Cells = make([]*Cell, upper) for i := 0; i < upper; i++ { cell = new(Cell) cell.Value = "" row.Cells[i] = cell } return row }
go
func makeRowFromRaw(rawrow xlsxRow, sheet *Sheet) *Row { var upper int var row *Row var cell *Cell row = new(Row) row.Sheet = sheet upper = -1 for _, rawcell := range rawrow.C { if rawcell.R != "" { x, _, error := GetCoordsFromCellIDString(rawcell.R) if error != nil { panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R)) } if x > upper { upper = x } continue } upper++ } upper++ row.OutlineLevel = rawrow.OutlineLevel row.Cells = make([]*Cell, upper) for i := 0; i < upper; i++ { cell = new(Cell) cell.Value = "" row.Cells[i] = cell } return row }
[ "func", "makeRowFromRaw", "(", "rawrow", "xlsxRow", ",", "sheet", "*", "Sheet", ")", "*", "Row", "{", "var", "upper", "int", "\n", "var", "row", "*", "Row", "\n", "var", "cell", "*", "Cell", "\n\n", "row", "=", "new", "(", "Row", ")", "\n", "row", ".", "Sheet", "=", "sheet", "\n", "upper", "=", "-", "1", "\n\n", "for", "_", ",", "rawcell", ":=", "range", "rawrow", ".", "C", "{", "if", "rawcell", ".", "R", "!=", "\"", "\"", "{", "x", ",", "_", ",", "error", ":=", "GetCoordsFromCellIDString", "(", "rawcell", ".", "R", ")", "\n", "if", "error", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "rawcell", ".", "R", ")", ")", "\n", "}", "\n", "if", "x", ">", "upper", "{", "upper", "=", "x", "\n", "}", "\n", "continue", "\n", "}", "\n", "upper", "++", "\n", "}", "\n", "upper", "++", "\n\n", "row", ".", "OutlineLevel", "=", "rawrow", ".", "OutlineLevel", "\n\n", "row", ".", "Cells", "=", "make", "(", "[", "]", "*", "Cell", ",", "upper", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "upper", ";", "i", "++", "{", "cell", "=", "new", "(", "Cell", ")", "\n", "cell", ".", "Value", "=", "\"", "\"", "\n", "row", ".", "Cells", "[", "i", "]", "=", "cell", "\n", "}", "\n", "return", "row", "\n", "}" ]
// makeRowFromRaw returns the Row representation of the xlsxRow.
[ "makeRowFromRaw", "returns", "the", "Row", "representation", "of", "the", "xlsxRow", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L301-L334
train
tealeg/xlsx
lib.go
fillCellDataFromInlineString
func fillCellDataFromInlineString(rawcell xlsxC, cell *Cell) { cell.Value = "" if rawcell.Is != nil { if rawcell.Is.T != "" { cell.Value = strings.Trim(rawcell.Is.T, " \t\n\r") } else { for _, r := range rawcell.Is.R { cell.Value += r.T } } } }
go
func fillCellDataFromInlineString(rawcell xlsxC, cell *Cell) { cell.Value = "" if rawcell.Is != nil { if rawcell.Is.T != "" { cell.Value = strings.Trim(rawcell.Is.T, " \t\n\r") } else { for _, r := range rawcell.Is.R { cell.Value += r.T } } } }
[ "func", "fillCellDataFromInlineString", "(", "rawcell", "xlsxC", ",", "cell", "*", "Cell", ")", "{", "cell", ".", "Value", "=", "\"", "\"", "\n", "if", "rawcell", ".", "Is", "!=", "nil", "{", "if", "rawcell", ".", "Is", ".", "T", "!=", "\"", "\"", "{", "cell", ".", "Value", "=", "strings", ".", "Trim", "(", "rawcell", ".", "Is", ".", "T", ",", "\"", "\\t", "\\n", "\\r", "\"", ")", "\n", "}", "else", "{", "for", "_", ",", "r", ":=", "range", "rawcell", ".", "Is", ".", "R", "{", "cell", ".", "Value", "+=", "r", ".", "T", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// fillCellDataFromInlineString attempts to get inline string data and put it into a Cell.
[ "fillCellDataFromInlineString", "attempts", "to", "get", "inline", "string", "data", "and", "put", "it", "into", "a", "Cell", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L509-L520
train
tealeg/xlsx
lib.go
readSheetsFromZipFile
func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string, rowLimit int) (map[string]*Sheet, []*Sheet, error) { var workbook *xlsxWorkbook var err error var rc io.ReadCloser var decoder *xml.Decoder var sheetCount int workbook = new(xlsxWorkbook) rc, err = f.Open() if err != nil { return nil, nil, err } decoder = xml.NewDecoder(rc) err = decoder.Decode(workbook) if err != nil { return nil, nil, err } file.Date1904 = workbook.WorkbookPr.Date1904 for entryNum := range workbook.DefinedNames.DefinedName { file.DefinedNames = append(file.DefinedNames, &workbook.DefinedNames.DefinedName[entryNum]) } // Only try and read sheets that have corresponding files. // Notably this excludes chartsheets don't right now var workbookSheets []xlsxSheet for _, sheet := range workbook.Sheets.Sheet { if f := worksheetFileForSheet(sheet, file.worksheets, sheetXMLMap); f != nil { workbookSheets = append(workbookSheets, sheet) } } sheetCount = len(workbookSheets) sheetsByName := make(map[string]*Sheet, sheetCount) sheets := make([]*Sheet, sheetCount) sheetChan := make(chan *indexedSheet, sheetCount) go func() { defer close(sheetChan) err = nil for i, rawsheet := range workbookSheets { if err := readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap, rowLimit); err != nil { return } } }() for j := 0; j < sheetCount; j++ { sheet := <-sheetChan if sheet.Error != nil { return nil, nil, sheet.Error } sheetName := workbookSheets[sheet.Index].Name sheetsByName[sheetName] = sheet.Sheet sheet.Sheet.Name = sheetName sheets[sheet.Index] = sheet.Sheet } return sheetsByName, sheets, nil }
go
func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string, rowLimit int) (map[string]*Sheet, []*Sheet, error) { var workbook *xlsxWorkbook var err error var rc io.ReadCloser var decoder *xml.Decoder var sheetCount int workbook = new(xlsxWorkbook) rc, err = f.Open() if err != nil { return nil, nil, err } decoder = xml.NewDecoder(rc) err = decoder.Decode(workbook) if err != nil { return nil, nil, err } file.Date1904 = workbook.WorkbookPr.Date1904 for entryNum := range workbook.DefinedNames.DefinedName { file.DefinedNames = append(file.DefinedNames, &workbook.DefinedNames.DefinedName[entryNum]) } // Only try and read sheets that have corresponding files. // Notably this excludes chartsheets don't right now var workbookSheets []xlsxSheet for _, sheet := range workbook.Sheets.Sheet { if f := worksheetFileForSheet(sheet, file.worksheets, sheetXMLMap); f != nil { workbookSheets = append(workbookSheets, sheet) } } sheetCount = len(workbookSheets) sheetsByName := make(map[string]*Sheet, sheetCount) sheets := make([]*Sheet, sheetCount) sheetChan := make(chan *indexedSheet, sheetCount) go func() { defer close(sheetChan) err = nil for i, rawsheet := range workbookSheets { if err := readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap, rowLimit); err != nil { return } } }() for j := 0; j < sheetCount; j++ { sheet := <-sheetChan if sheet.Error != nil { return nil, nil, sheet.Error } sheetName := workbookSheets[sheet.Index].Name sheetsByName[sheetName] = sheet.Sheet sheet.Sheet.Name = sheetName sheets[sheet.Index] = sheet.Sheet } return sheetsByName, sheets, nil }
[ "func", "readSheetsFromZipFile", "(", "f", "*", "zip", ".", "File", ",", "file", "*", "File", ",", "sheetXMLMap", "map", "[", "string", "]", "string", ",", "rowLimit", "int", ")", "(", "map", "[", "string", "]", "*", "Sheet", ",", "[", "]", "*", "Sheet", ",", "error", ")", "{", "var", "workbook", "*", "xlsxWorkbook", "\n", "var", "err", "error", "\n", "var", "rc", "io", ".", "ReadCloser", "\n", "var", "decoder", "*", "xml", ".", "Decoder", "\n", "var", "sheetCount", "int", "\n", "workbook", "=", "new", "(", "xlsxWorkbook", ")", "\n", "rc", ",", "err", "=", "f", ".", "Open", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "decoder", "=", "xml", ".", "NewDecoder", "(", "rc", ")", "\n", "err", "=", "decoder", ".", "Decode", "(", "workbook", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "file", ".", "Date1904", "=", "workbook", ".", "WorkbookPr", ".", "Date1904", "\n\n", "for", "entryNum", ":=", "range", "workbook", ".", "DefinedNames", ".", "DefinedName", "{", "file", ".", "DefinedNames", "=", "append", "(", "file", ".", "DefinedNames", ",", "&", "workbook", ".", "DefinedNames", ".", "DefinedName", "[", "entryNum", "]", ")", "\n", "}", "\n\n", "// Only try and read sheets that have corresponding files.", "// Notably this excludes chartsheets don't right now", "var", "workbookSheets", "[", "]", "xlsxSheet", "\n", "for", "_", ",", "sheet", ":=", "range", "workbook", ".", "Sheets", ".", "Sheet", "{", "if", "f", ":=", "worksheetFileForSheet", "(", "sheet", ",", "file", ".", "worksheets", ",", "sheetXMLMap", ")", ";", "f", "!=", "nil", "{", "workbookSheets", "=", "append", "(", "workbookSheets", ",", "sheet", ")", "\n", "}", "\n", "}", "\n", "sheetCount", "=", "len", "(", "workbookSheets", ")", "\n", "sheetsByName", ":=", "make", "(", "map", "[", "string", "]", "*", "Sheet", ",", "sheetCount", ")", "\n", "sheets", ":=", "make", "(", "[", "]", "*", "Sheet", ",", "sheetCount", ")", "\n", "sheetChan", ":=", "make", "(", "chan", "*", "indexedSheet", ",", "sheetCount", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "close", "(", "sheetChan", ")", "\n", "err", "=", "nil", "\n", "for", "i", ",", "rawsheet", ":=", "range", "workbookSheets", "{", "if", "err", ":=", "readSheetFromFile", "(", "sheetChan", ",", "i", ",", "rawsheet", ",", "file", ",", "sheetXMLMap", ",", "rowLimit", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "for", "j", ":=", "0", ";", "j", "<", "sheetCount", ";", "j", "++", "{", "sheet", ":=", "<-", "sheetChan", "\n", "if", "sheet", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "sheet", ".", "Error", "\n", "}", "\n", "sheetName", ":=", "workbookSheets", "[", "sheet", ".", "Index", "]", ".", "Name", "\n", "sheetsByName", "[", "sheetName", "]", "=", "sheet", ".", "Sheet", "\n", "sheet", ".", "Sheet", ".", "Name", "=", "sheetName", "\n", "sheets", "[", "sheet", ".", "Index", "]", "=", "sheet", ".", "Sheet", "\n", "}", "\n", "return", "sheetsByName", ",", "sheets", ",", "nil", "\n", "}" ]
// readSheetsFromZipFile is an internal helper function that loops // over the Worksheets defined in the XSLXWorkbook and loads them into // Sheet objects stored in the Sheets slice of a xlsx.File struct.
[ "readSheetsFromZipFile", "is", "an", "internal", "helper", "function", "that", "loops", "over", "the", "Worksheets", "defined", "in", "the", "XSLXWorkbook", "and", "loads", "them", "into", "Sheet", "objects", "stored", "in", "the", "Sheets", "slice", "of", "a", "xlsx", ".", "File", "struct", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L777-L833
train
tealeg/xlsx
lib.go
truncateSheetXML
func truncateSheetXML(r io.Reader, rowLimit int) (io.Reader, error) { var rowCount int var token xml.Token var readErr error output := new(bytes.Buffer) r = io.TeeReader(r, output) decoder := xml.NewDecoder(r) for { token, readErr = decoder.Token() if readErr == io.EOF { break } else if readErr != nil { return nil, readErr } end, ok := token.(xml.EndElement) if ok && end.Name.Local == "row" { rowCount++ if rowCount >= rowLimit { break } } } offset := decoder.InputOffset() output.Truncate(int(offset)) if readErr != io.EOF { _, err := output.Write([]byte(sheetEnding)) if err != nil { return nil, err } } return output, nil }
go
func truncateSheetXML(r io.Reader, rowLimit int) (io.Reader, error) { var rowCount int var token xml.Token var readErr error output := new(bytes.Buffer) r = io.TeeReader(r, output) decoder := xml.NewDecoder(r) for { token, readErr = decoder.Token() if readErr == io.EOF { break } else if readErr != nil { return nil, readErr } end, ok := token.(xml.EndElement) if ok && end.Name.Local == "row" { rowCount++ if rowCount >= rowLimit { break } } } offset := decoder.InputOffset() output.Truncate(int(offset)) if readErr != io.EOF { _, err := output.Write([]byte(sheetEnding)) if err != nil { return nil, err } } return output, nil }
[ "func", "truncateSheetXML", "(", "r", "io", ".", "Reader", ",", "rowLimit", "int", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "var", "rowCount", "int", "\n", "var", "token", "xml", ".", "Token", "\n", "var", "readErr", "error", "\n\n", "output", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "r", "=", "io", ".", "TeeReader", "(", "r", ",", "output", ")", "\n", "decoder", ":=", "xml", ".", "NewDecoder", "(", "r", ")", "\n\n", "for", "{", "token", ",", "readErr", "=", "decoder", ".", "Token", "(", ")", "\n", "if", "readErr", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "readErr", "!=", "nil", "{", "return", "nil", ",", "readErr", "\n", "}", "\n", "end", ",", "ok", ":=", "token", ".", "(", "xml", ".", "EndElement", ")", "\n", "if", "ok", "&&", "end", ".", "Name", ".", "Local", "==", "\"", "\"", "{", "rowCount", "++", "\n", "if", "rowCount", ">=", "rowLimit", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "offset", ":=", "decoder", ".", "InputOffset", "(", ")", "\n", "output", ".", "Truncate", "(", "int", "(", "offset", ")", ")", "\n\n", "if", "readErr", "!=", "io", ".", "EOF", "{", "_", ",", "err", ":=", "output", ".", "Write", "(", "[", "]", "byte", "(", "sheetEnding", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "output", ",", "nil", "\n", "}" ]
// truncateSheetXML will take in a reader to an XML sheet file and will return a reader that will read an equivalent // XML sheet file with only the number of rows specified. This greatly speeds up XML unmarshalling when only // a few rows need to be read from a large sheet. // When sheets are truncated, all formatting present after the sheetData tag will be lost, but all of this formatting // is related to printing and visibility, and is out of scope for most purposes of this library.
[ "truncateSheetXML", "will", "take", "in", "a", "reader", "to", "an", "XML", "sheet", "file", "and", "will", "return", "a", "reader", "that", "will", "read", "an", "equivalent", "XML", "sheet", "file", "with", "only", "the", "number", "of", "rows", "specified", ".", "This", "greatly", "speeds", "up", "XML", "unmarshalling", "when", "only", "a", "few", "rows", "need", "to", "be", "read", "from", "a", "large", "sheet", ".", "When", "sheets", "are", "truncated", "all", "formatting", "present", "after", "the", "sheetData", "tag", "will", "be", "lost", "but", "all", "of", "this", "formatting", "is", "related", "to", "printing", "and", "visibility", "and", "is", "out", "of", "scope", "for", "most", "purposes", "of", "this", "library", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L1096-L1131
train
tealeg/xlsx
file.go
FileToSliceUnmerged
func FileToSliceUnmerged(path string) ([][][]string, error) { f, err := OpenFile(path) if err != nil { return nil, err } return f.ToSliceUnmerged() }
go
func FileToSliceUnmerged(path string) ([][][]string, error) { f, err := OpenFile(path) if err != nil { return nil, err } return f.ToSliceUnmerged() }
[ "func", "FileToSliceUnmerged", "(", "path", "string", ")", "(", "[", "]", "[", "]", "[", "]", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "OpenFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "f", ".", "ToSliceUnmerged", "(", ")", "\n", "}" ]
// FileToSliceUnmerged is a wrapper around File.ToSliceUnmerged. // It returns the raw data contained in an Excel XLSX file as three // dimensional slice. Merged cells will be unmerged. Covered cells become the // values of theirs origins.
[ "FileToSliceUnmerged", "is", "a", "wrapper", "around", "File", ".", "ToSliceUnmerged", ".", "It", "returns", "the", "raw", "data", "contained", "in", "an", "Excel", "XLSX", "file", "as", "three", "dimensional", "slice", ".", "Merged", "cells", "will", "be", "unmerged", ".", "Covered", "cells", "become", "the", "values", "of", "theirs", "origins", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L112-L118
train
tealeg/xlsx
sheet.go
AddRowAtIndex
func (s *Sheet) AddRowAtIndex(index int) (*Row, error) { if index < 0 || index > len(s.Rows) { return nil, errors.New("AddRowAtIndex: index out of bounds") } row := &Row{Sheet: s} s.Rows = append(s.Rows, nil) if index < len(s.Rows) { copy(s.Rows[index+1:], s.Rows[index:]) } s.Rows[index] = row if len(s.Rows) > s.MaxRow { s.MaxRow = len(s.Rows) } return row, nil }
go
func (s *Sheet) AddRowAtIndex(index int) (*Row, error) { if index < 0 || index > len(s.Rows) { return nil, errors.New("AddRowAtIndex: index out of bounds") } row := &Row{Sheet: s} s.Rows = append(s.Rows, nil) if index < len(s.Rows) { copy(s.Rows[index+1:], s.Rows[index:]) } s.Rows[index] = row if len(s.Rows) > s.MaxRow { s.MaxRow = len(s.Rows) } return row, nil }
[ "func", "(", "s", "*", "Sheet", ")", "AddRowAtIndex", "(", "index", "int", ")", "(", "*", "Row", ",", "error", ")", "{", "if", "index", "<", "0", "||", "index", ">", "len", "(", "s", ".", "Rows", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "row", ":=", "&", "Row", "{", "Sheet", ":", "s", "}", "\n", "s", ".", "Rows", "=", "append", "(", "s", ".", "Rows", ",", "nil", ")", "\n\n", "if", "index", "<", "len", "(", "s", ".", "Rows", ")", "{", "copy", "(", "s", ".", "Rows", "[", "index", "+", "1", ":", "]", ",", "s", ".", "Rows", "[", "index", ":", "]", ")", "\n", "}", "\n", "s", ".", "Rows", "[", "index", "]", "=", "row", "\n", "if", "len", "(", "s", ".", "Rows", ")", ">", "s", ".", "MaxRow", "{", "s", ".", "MaxRow", "=", "len", "(", "s", ".", "Rows", ")", "\n", "}", "\n", "return", "row", ",", "nil", "\n", "}" ]
// Add a new Row to a Sheet at a specific index
[ "Add", "a", "new", "Row", "to", "a", "Sheet", "at", "a", "specific", "index" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L60-L75
train
tealeg/xlsx
sheet.go
RemoveRowAtIndex
func (s *Sheet) RemoveRowAtIndex(index int) error { if index < 0 || index >= len(s.Rows) { return errors.New("RemoveRowAtIndex: index out of bounds") } s.Rows = append(s.Rows[:index], s.Rows[index+1:]...) return nil }
go
func (s *Sheet) RemoveRowAtIndex(index int) error { if index < 0 || index >= len(s.Rows) { return errors.New("RemoveRowAtIndex: index out of bounds") } s.Rows = append(s.Rows[:index], s.Rows[index+1:]...) return nil }
[ "func", "(", "s", "*", "Sheet", ")", "RemoveRowAtIndex", "(", "index", "int", ")", "error", "{", "if", "index", "<", "0", "||", "index", ">=", "len", "(", "s", ".", "Rows", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "s", ".", "Rows", "=", "append", "(", "s", ".", "Rows", "[", ":", "index", "]", ",", "s", ".", "Rows", "[", "index", "+", "1", ":", "]", "...", ")", "\n", "return", "nil", "\n", "}" ]
// Removes a row at a specific index
[ "Removes", "a", "row", "at", "a", "specific", "index" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L78-L84
train
tealeg/xlsx
sheet.go
handleMerged
func (s *Sheet) handleMerged() { merged := make(map[string]*Cell) for r, row := range s.Rows { for c, cell := range row.Cells { if cell.HMerge > 0 || cell.VMerge > 0 { coord := GetCellIDStringFromCoords(c, r) merged[coord] = cell } } } // This loop iterates over all cells that should be merged and applies the correct // borders to them depending on their position. If any cells required by the merge // are missing, they will be allocated by s.Cell(). for key, cell := range merged { maincol, mainrow, _ := GetCoordsFromCellIDString(key) for rownum := 0; rownum <= cell.VMerge; rownum++ { for colnum := 0; colnum <= cell.HMerge; colnum++ { // make cell s.Cell(mainrow+rownum, maincol+colnum) } } } }
go
func (s *Sheet) handleMerged() { merged := make(map[string]*Cell) for r, row := range s.Rows { for c, cell := range row.Cells { if cell.HMerge > 0 || cell.VMerge > 0 { coord := GetCellIDStringFromCoords(c, r) merged[coord] = cell } } } // This loop iterates over all cells that should be merged and applies the correct // borders to them depending on their position. If any cells required by the merge // are missing, they will be allocated by s.Cell(). for key, cell := range merged { maincol, mainrow, _ := GetCoordsFromCellIDString(key) for rownum := 0; rownum <= cell.VMerge; rownum++ { for colnum := 0; colnum <= cell.HMerge; colnum++ { // make cell s.Cell(mainrow+rownum, maincol+colnum) } } } }
[ "func", "(", "s", "*", "Sheet", ")", "handleMerged", "(", ")", "{", "merged", ":=", "make", "(", "map", "[", "string", "]", "*", "Cell", ")", "\n\n", "for", "r", ",", "row", ":=", "range", "s", ".", "Rows", "{", "for", "c", ",", "cell", ":=", "range", "row", ".", "Cells", "{", "if", "cell", ".", "HMerge", ">", "0", "||", "cell", ".", "VMerge", ">", "0", "{", "coord", ":=", "GetCellIDStringFromCoords", "(", "c", ",", "r", ")", "\n", "merged", "[", "coord", "]", "=", "cell", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// This loop iterates over all cells that should be merged and applies the correct", "// borders to them depending on their position. If any cells required by the merge", "// are missing, they will be allocated by s.Cell().", "for", "key", ",", "cell", ":=", "range", "merged", "{", "maincol", ",", "mainrow", ",", "_", ":=", "GetCoordsFromCellIDString", "(", "key", ")", "\n", "for", "rownum", ":=", "0", ";", "rownum", "<=", "cell", ".", "VMerge", ";", "rownum", "++", "{", "for", "colnum", ":=", "0", ";", "colnum", "<=", "cell", ".", "HMerge", ";", "colnum", "++", "{", "// make cell", "s", ".", "Cell", "(", "mainrow", "+", "rownum", ",", "maincol", "+", "colnum", ")", "\n\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// When merging cells, the cell may be the 'original' or the 'covered'. // First, figure out which cells are merge starting points. Then create // the necessary cells underlying the merge area. // Then go through all the underlying cells and apply the appropriate // border, based on the original cell.
[ "When", "merging", "cells", "the", "cell", "may", "be", "the", "original", "or", "the", "covered", ".", "First", "figure", "out", "which", "cells", "are", "merge", "starting", "points", ".", "Then", "create", "the", "necessary", "cells", "underlying", "the", "merge", "area", ".", "Then", "go", "through", "all", "the", "underlying", "cells", "and", "apply", "the", "appropriate", "border", "based", "on", "the", "original", "cell", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L175-L201
train
tealeg/xlsx
cell.go
GetTime
func (c *Cell) GetTime(date1904 bool) (t time.Time, err error) { f, err := c.Float() if err != nil { return t, err } return TimeFromExcelTime(f, date1904), nil }
go
func (c *Cell) GetTime(date1904 bool) (t time.Time, err error) { f, err := c.Float() if err != nil { return t, err } return TimeFromExcelTime(f, date1904), nil }
[ "func", "(", "c", "*", "Cell", ")", "GetTime", "(", "date1904", "bool", ")", "(", "t", "time", ".", "Time", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "c", ".", "Float", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "t", ",", "err", "\n", "}", "\n", "return", "TimeFromExcelTime", "(", "f", ",", "date1904", ")", ",", "nil", "\n", "}" ]
//GetTime returns the value of a Cell as a time.Time
[ "GetTime", "returns", "the", "value", "of", "a", "Cell", "as", "a", "time", ".", "Time" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L111-L117
train
tealeg/xlsx
cell.go
SetDateWithOptions
func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions) { _, offset := t.In(options.Location).Zone() t = time.Unix(t.Unix()+int64(offset), 0) c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC), c.date1904), options.ExcelTimeFormat) }
go
func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions) { _, offset := t.In(options.Location).Zone() t = time.Unix(t.Unix()+int64(offset), 0) c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC), c.date1904), options.ExcelTimeFormat) }
[ "func", "(", "c", "*", "Cell", ")", "SetDateWithOptions", "(", "t", "time", ".", "Time", ",", "options", "DateTimeOptions", ")", "{", "_", ",", "offset", ":=", "t", ".", "In", "(", "options", ".", "Location", ")", ".", "Zone", "(", ")", "\n", "t", "=", "time", ".", "Unix", "(", "t", ".", "Unix", "(", ")", "+", "int64", "(", "offset", ")", ",", "0", ")", "\n", "c", ".", "SetDateTimeWithFormat", "(", "TimeToExcelTime", "(", "t", ".", "In", "(", "timeLocationUTC", ")", ",", "c", ".", "date1904", ")", ",", "options", ".", "ExcelTimeFormat", ")", "\n", "}" ]
// SetDateWithOptions allows for more granular control when exporting dates and times
[ "SetDateWithOptions", "allows", "for", "more", "granular", "control", "when", "exporting", "dates", "and", "times" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L177-L181
train
tealeg/xlsx
cell.go
setNumeric
func (c *Cell) setNumeric(s string) { c.Value = s c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL] c.formula = "" c.cellType = CellTypeNumeric }
go
func (c *Cell) setNumeric(s string) { c.Value = s c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL] c.formula = "" c.cellType = CellTypeNumeric }
[ "func", "(", "c", "*", "Cell", ")", "setNumeric", "(", "s", "string", ")", "{", "c", ".", "Value", "=", "s", "\n", "c", ".", "NumFmt", "=", "builtInNumFmt", "[", "builtInNumFmtIndex_GENERAL", "]", "\n", "c", ".", "formula", "=", "\"", "\"", "\n", "c", ".", "cellType", "=", "CellTypeNumeric", "\n", "}" ]
// setNumeric sets a cell's value to a number
[ "setNumeric", "sets", "a", "cell", "s", "value", "to", "a", "number" ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L261-L266
train
tealeg/xlsx
cell.go
getNumberFormat
func (c *Cell) getNumberFormat() *parsedNumberFormat { if c.parsedNumFmt == nil || c.parsedNumFmt.numFmt != c.NumFmt { c.parsedNumFmt = parseFullNumberFormatString(c.NumFmt) } return c.parsedNumFmt }
go
func (c *Cell) getNumberFormat() *parsedNumberFormat { if c.parsedNumFmt == nil || c.parsedNumFmt.numFmt != c.NumFmt { c.parsedNumFmt = parseFullNumberFormatString(c.NumFmt) } return c.parsedNumFmt }
[ "func", "(", "c", "*", "Cell", ")", "getNumberFormat", "(", ")", "*", "parsedNumberFormat", "{", "if", "c", ".", "parsedNumFmt", "==", "nil", "||", "c", ".", "parsedNumFmt", ".", "numFmt", "!=", "c", ".", "NumFmt", "{", "c", ".", "parsedNumFmt", "=", "parseFullNumberFormatString", "(", "c", ".", "NumFmt", ")", "\n", "}", "\n", "return", "c", ".", "parsedNumFmt", "\n", "}" ]
// getNumberFormat will update the parsedNumFmt struct if it has become out of date, since a cell's NumFmt string is a // public field that could be edited by clients.
[ "getNumberFormat", "will", "update", "the", "parsedNumFmt", "struct", "if", "it", "has", "become", "out", "of", "date", "since", "a", "cell", "s", "NumFmt", "string", "is", "a", "public", "field", "that", "could", "be", "edited", "by", "clients", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L357-L362
train
tealeg/xlsx
cell.go
FormattedValue
func (c *Cell) FormattedValue() (string, error) { fullFormat := c.getNumberFormat() returnVal, err := fullFormat.FormatValue(c) if fullFormat.parseEncounteredError != nil { return returnVal, *fullFormat.parseEncounteredError } return returnVal, err }
go
func (c *Cell) FormattedValue() (string, error) { fullFormat := c.getNumberFormat() returnVal, err := fullFormat.FormatValue(c) if fullFormat.parseEncounteredError != nil { return returnVal, *fullFormat.parseEncounteredError } return returnVal, err }
[ "func", "(", "c", "*", "Cell", ")", "FormattedValue", "(", ")", "(", "string", ",", "error", ")", "{", "fullFormat", ":=", "c", ".", "getNumberFormat", "(", ")", "\n", "returnVal", ",", "err", ":=", "fullFormat", ".", "FormatValue", "(", "c", ")", "\n", "if", "fullFormat", ".", "parseEncounteredError", "!=", "nil", "{", "return", "returnVal", ",", "*", "fullFormat", ".", "parseEncounteredError", "\n", "}", "\n", "return", "returnVal", ",", "err", "\n", "}" ]
// FormattedValue returns a value, and possibly an error condition // from a Cell. If it is possible to apply a format to the cell // value, it will do so, if not then an error will be returned, along // with the raw value of the Cell.
[ "FormattedValue", "returns", "a", "value", "and", "possibly", "an", "error", "condition", "from", "a", "Cell", ".", "If", "it", "is", "possible", "to", "apply", "a", "format", "to", "the", "cell", "value", "it", "will", "do", "so", "if", "not", "then", "an", "error", "will", "be", "returned", "along", "with", "the", "raw", "value", "of", "the", "Cell", "." ]
b7005b5d48cbd240baa323f68fb644fe072ef088
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L368-L375
train
eclipse/paho.mqtt.golang
packets/connect.go
Validate
func (c *ConnectPacket) Validate() byte { if c.PasswordFlag && !c.UsernameFlag { return ErrRefusedBadUsernameOrPassword } if c.ReservedBit != 0 { //Bad reserved bit return ErrProtocolViolation } if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) { //Mismatched or unsupported protocol version return ErrRefusedBadProtocolVersion } if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" { //Bad protocol name return ErrProtocolViolation } if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 { //Bad size field return ErrProtocolViolation } if len(c.ClientIdentifier) == 0 && !c.CleanSession { //Bad client identifier return ErrRefusedIDRejected } return Accepted }
go
func (c *ConnectPacket) Validate() byte { if c.PasswordFlag && !c.UsernameFlag { return ErrRefusedBadUsernameOrPassword } if c.ReservedBit != 0 { //Bad reserved bit return ErrProtocolViolation } if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) { //Mismatched or unsupported protocol version return ErrRefusedBadProtocolVersion } if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" { //Bad protocol name return ErrProtocolViolation } if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 { //Bad size field return ErrProtocolViolation } if len(c.ClientIdentifier) == 0 && !c.CleanSession { //Bad client identifier return ErrRefusedIDRejected } return Accepted }
[ "func", "(", "c", "*", "ConnectPacket", ")", "Validate", "(", ")", "byte", "{", "if", "c", ".", "PasswordFlag", "&&", "!", "c", ".", "UsernameFlag", "{", "return", "ErrRefusedBadUsernameOrPassword", "\n", "}", "\n", "if", "c", ".", "ReservedBit", "!=", "0", "{", "//Bad reserved bit", "return", "ErrProtocolViolation", "\n", "}", "\n", "if", "(", "c", ".", "ProtocolName", "==", "\"", "\"", "&&", "c", ".", "ProtocolVersion", "!=", "3", ")", "||", "(", "c", ".", "ProtocolName", "==", "\"", "\"", "&&", "c", ".", "ProtocolVersion", "!=", "4", ")", "{", "//Mismatched or unsupported protocol version", "return", "ErrRefusedBadProtocolVersion", "\n", "}", "\n", "if", "c", ".", "ProtocolName", "!=", "\"", "\"", "&&", "c", ".", "ProtocolName", "!=", "\"", "\"", "{", "//Bad protocol name", "return", "ErrProtocolViolation", "\n", "}", "\n", "if", "len", "(", "c", ".", "ClientIdentifier", ")", ">", "65535", "||", "len", "(", "c", ".", "Username", ")", ">", "65535", "||", "len", "(", "c", ".", "Password", ")", ">", "65535", "{", "//Bad size field", "return", "ErrProtocolViolation", "\n", "}", "\n", "if", "len", "(", "c", ".", "ClientIdentifier", ")", "==", "0", "&&", "!", "c", ".", "CleanSession", "{", "//Bad client identifier", "return", "ErrRefusedIDRejected", "\n", "}", "\n", "return", "Accepted", "\n", "}" ]
//Validate performs validation of the fields of a Connect packet
[ "Validate", "performs", "validation", "of", "the", "fields", "of", "a", "Connect", "packet" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/connect.go#L123-L148
train
eclipse/paho.mqtt.golang
store.go
persistInbound
func persistInbound(s Store, m packets.ControlPacket) { switch m.Details().Qos { case 0: switch m.(type) { case *packets.PubackPacket, *packets.SubackPacket, *packets.UnsubackPacket, *packets.PubcompPacket: // Received a puback. delete matching publish // from obound s.Del(outboundKeyFromMID(m.Details().MessageID)) case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket: default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 1: switch m.(type) { case *packets.PublishPacket, *packets.PubrelPacket: // Received a publish. store it in ibound // until puback sent s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 2: switch m.(type) { case *packets.PublishPacket: // Received a publish. store it in ibound // until pubrel received s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } } }
go
func persistInbound(s Store, m packets.ControlPacket) { switch m.Details().Qos { case 0: switch m.(type) { case *packets.PubackPacket, *packets.SubackPacket, *packets.UnsubackPacket, *packets.PubcompPacket: // Received a puback. delete matching publish // from obound s.Del(outboundKeyFromMID(m.Details().MessageID)) case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket: default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 1: switch m.(type) { case *packets.PublishPacket, *packets.PubrelPacket: // Received a publish. store it in ibound // until puback sent s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 2: switch m.(type) { case *packets.PublishPacket: // Received a publish. store it in ibound // until pubrel received s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } } }
[ "func", "persistInbound", "(", "s", "Store", ",", "m", "packets", ".", "ControlPacket", ")", "{", "switch", "m", ".", "Details", "(", ")", ".", "Qos", "{", "case", "0", ":", "switch", "m", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "PubackPacket", ",", "*", "packets", ".", "SubackPacket", ",", "*", "packets", ".", "UnsubackPacket", ",", "*", "packets", ".", "PubcompPacket", ":", "// Received a puback. delete matching publish", "// from obound", "s", ".", "Del", "(", "outboundKeyFromMID", "(", "m", ".", "Details", "(", ")", ".", "MessageID", ")", ")", "\n", "case", "*", "packets", ".", "PublishPacket", ",", "*", "packets", ".", "PubrecPacket", ",", "*", "packets", ".", "PingrespPacket", ",", "*", "packets", ".", "ConnackPacket", ":", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "1", ":", "switch", "m", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "PublishPacket", ",", "*", "packets", ".", "PubrelPacket", ":", "// Received a publish. store it in ibound", "// until puback sent", "s", ".", "Put", "(", "inboundKeyFromMID", "(", "m", ".", "Details", "(", ")", ".", "MessageID", ")", ",", "m", ")", "\n", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "2", ":", "switch", "m", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "PublishPacket", ":", "// Received a publish. store it in ibound", "// until pubrel received", "s", ".", "Put", "(", "inboundKeyFromMID", "(", "m", ".", "Details", "(", ")", ".", "MessageID", ")", ",", "m", ")", "\n", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// govern which incoming messages are persisted
[ "govern", "which", "incoming", "messages", "are", "persisted" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/store.go#L105-L136
train
eclipse/paho.mqtt.golang
options.go
SetClientID
func (o *ClientOptions) SetClientID(id string) *ClientOptions { o.ClientID = id return o }
go
func (o *ClientOptions) SetClientID(id string) *ClientOptions { o.ClientID = id return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetClientID", "(", "id", "string", ")", "*", "ClientOptions", "{", "o", ".", "ClientID", "=", "id", "\n", "return", "o", "\n", "}" ]
// SetClientID will set the client id to be used by this client when // connecting to the MQTT broker. According to the MQTT v3.1 specification, // a client id mus be no longer than 23 characters.
[ "SetClientID", "will", "set", "the", "client", "id", "to", "be", "used", "by", "this", "client", "when", "connecting", "to", "the", "MQTT", "broker", ".", "According", "to", "the", "MQTT", "v3", ".", "1", "specification", "a", "client", "id", "mus", "be", "no", "longer", "than", "23", "characters", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L153-L156
train
eclipse/paho.mqtt.golang
options.go
SetCleanSession
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions { o.CleanSession = clean return o }
go
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions { o.CleanSession = clean return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetCleanSession", "(", "clean", "bool", ")", "*", "ClientOptions", "{", "o", ".", "CleanSession", "=", "clean", "\n", "return", "o", "\n", "}" ]
// SetCleanSession will set the "clean session" flag in the connect message // when this client connects to an MQTT broker. By setting this flag, you are // indicating that no messages saved by the broker for this client should be // delivered. Any messages that were going to be sent by this client before // diconnecting previously but didn't will not be sent upon connecting to the // broker.
[ "SetCleanSession", "will", "set", "the", "clean", "session", "flag", "in", "the", "connect", "message", "when", "this", "client", "connects", "to", "an", "MQTT", "broker", ".", "By", "setting", "this", "flag", "you", "are", "indicating", "that", "no", "messages", "saved", "by", "the", "broker", "for", "this", "client", "should", "be", "delivered", ".", "Any", "messages", "that", "were", "going", "to", "be", "sent", "by", "this", "client", "before", "diconnecting", "previously", "but", "didn", "t", "will", "not", "be", "sent", "upon", "connecting", "to", "the", "broker", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L189-L192
train
eclipse/paho.mqtt.golang
options.go
SetOrderMatters
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions { o.Order = order return o }
go
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions { o.Order = order return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetOrderMatters", "(", "order", "bool", ")", "*", "ClientOptions", "{", "o", ".", "Order", "=", "order", "\n", "return", "o", "\n", "}" ]
// SetOrderMatters will set the message routing to guarantee order within // each QoS level. By default, this value is true. If set to false, // this flag indicates that messages can be delivered asynchronously // from the client to the application and possibly arrive out of order.
[ "SetOrderMatters", "will", "set", "the", "message", "routing", "to", "guarantee", "order", "within", "each", "QoS", "level", ".", "By", "default", "this", "value", "is", "true", ".", "If", "set", "to", "false", "this", "flag", "indicates", "that", "messages", "can", "be", "delivered", "asynchronously", "from", "the", "client", "to", "the", "application", "and", "possibly", "arrive", "out", "of", "order", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L198-L201
train
eclipse/paho.mqtt.golang
options.go
SetStore
func (o *ClientOptions) SetStore(s Store) *ClientOptions { o.Store = s return o }
go
func (o *ClientOptions) SetStore(s Store) *ClientOptions { o.Store = s return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetStore", "(", "s", "Store", ")", "*", "ClientOptions", "{", "o", ".", "Store", "=", "s", "\n", "return", "o", "\n", "}" ]
// SetStore will set the implementation of the Store interface // used to provide message persistence in cases where QoS levels // QoS_ONE or QoS_TWO are used. If no store is provided, then the // client will use MemoryStore by default.
[ "SetStore", "will", "set", "the", "implementation", "of", "the", "Store", "interface", "used", "to", "provide", "message", "persistence", "in", "cases", "where", "QoS", "levels", "QoS_ONE", "or", "QoS_TWO", "are", "used", ".", "If", "no", "store", "is", "provided", "then", "the", "client", "will", "use", "MemoryStore", "by", "default", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L215-L218
train
eclipse/paho.mqtt.golang
options.go
SetProtocolVersion
func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions { if (pv >= 3 && pv <= 4) || (pv > 0x80) { o.ProtocolVersion = pv o.protocolVersionExplicit = true } return o }
go
func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions { if (pv >= 3 && pv <= 4) || (pv > 0x80) { o.ProtocolVersion = pv o.protocolVersionExplicit = true } return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetProtocolVersion", "(", "pv", "uint", ")", "*", "ClientOptions", "{", "if", "(", "pv", ">=", "3", "&&", "pv", "<=", "4", ")", "||", "(", "pv", ">", "0x80", ")", "{", "o", ".", "ProtocolVersion", "=", "pv", "\n", "o", ".", "protocolVersionExplicit", "=", "true", "\n", "}", "\n", "return", "o", "\n", "}" ]
// SetProtocolVersion sets the MQTT version to be used to connect to the // broker. Legitimate values are currently 3 - MQTT 3.1 or 4 - MQTT 3.1.1
[ "SetProtocolVersion", "sets", "the", "MQTT", "version", "to", "be", "used", "to", "connect", "to", "the", "broker", ".", "Legitimate", "values", "are", "currently", "3", "-", "MQTT", "3", ".", "1", "or", "4", "-", "MQTT", "3", ".", "1", ".", "1" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L239-L245
train
eclipse/paho.mqtt.golang
options.go
SetOnConnectHandler
func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions { o.OnConnect = onConn return o }
go
func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions { o.OnConnect = onConn return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetOnConnectHandler", "(", "onConn", "OnConnectHandler", ")", "*", "ClientOptions", "{", "o", ".", "OnConnect", "=", "onConn", "\n", "return", "o", "\n", "}" ]
// SetOnConnectHandler sets the function to be called when the client is connected. Both // at initial connection time and upon automatic reconnect.
[ "SetOnConnectHandler", "sets", "the", "function", "to", "be", "called", "when", "the", "client", "is", "connected", ".", "Both", "at", "initial", "connection", "time", "and", "upon", "automatic", "reconnect", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L284-L287
train
eclipse/paho.mqtt.golang
options.go
SetConnectionLostHandler
func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions { o.OnConnectionLost = onLost return o }
go
func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions { o.OnConnectionLost = onLost return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetConnectionLostHandler", "(", "onLost", "ConnectionLostHandler", ")", "*", "ClientOptions", "{", "o", ".", "OnConnectionLost", "=", "onLost", "\n", "return", "o", "\n", "}" ]
// SetConnectionLostHandler will set the OnConnectionLost callback to be executed // in the case where the client unexpectedly loses connection with the MQTT broker.
[ "SetConnectionLostHandler", "will", "set", "the", "OnConnectionLost", "callback", "to", "be", "executed", "in", "the", "case", "where", "the", "client", "unexpectedly", "loses", "connection", "with", "the", "MQTT", "broker", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L291-L294
train
eclipse/paho.mqtt.golang
options.go
SetWriteTimeout
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions { o.WriteTimeout = t return o }
go
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions { o.WriteTimeout = t return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetWriteTimeout", "(", "t", "time", ".", "Duration", ")", "*", "ClientOptions", "{", "o", ".", "WriteTimeout", "=", "t", "\n", "return", "o", "\n", "}" ]
// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a // timeout error. A duration of 0 never times out. Default 30 seconds
[ "SetWriteTimeout", "puts", "a", "limit", "on", "how", "long", "a", "mqtt", "publish", "should", "block", "until", "it", "unblocks", "with", "a", "timeout", "error", ".", "A", "duration", "of", "0", "never", "times", "out", ".", "Default", "30", "seconds" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L298-L301
train
eclipse/paho.mqtt.golang
options.go
SetMaxReconnectInterval
func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions { o.MaxReconnectInterval = t return o }
go
func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions { o.MaxReconnectInterval = t return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetMaxReconnectInterval", "(", "t", "time", ".", "Duration", ")", "*", "ClientOptions", "{", "o", ".", "MaxReconnectInterval", "=", "t", "\n", "return", "o", "\n", "}" ]
// SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts // when connection is lost
[ "SetMaxReconnectInterval", "sets", "the", "maximum", "time", "that", "will", "be", "waited", "between", "reconnection", "attempts", "when", "connection", "is", "lost" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L313-L316
train
eclipse/paho.mqtt.golang
options.go
SetAutoReconnect
func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions { o.AutoReconnect = a return o }
go
func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions { o.AutoReconnect = a return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetAutoReconnect", "(", "a", "bool", ")", "*", "ClientOptions", "{", "o", ".", "AutoReconnect", "=", "a", "\n", "return", "o", "\n", "}" ]
// SetAutoReconnect sets whether the automatic reconnection logic should be used // when the connection is lost, even if disabled the ConnectionLostHandler is still // called
[ "SetAutoReconnect", "sets", "whether", "the", "automatic", "reconnection", "logic", "should", "be", "used", "when", "the", "connection", "is", "lost", "even", "if", "disabled", "the", "ConnectionLostHandler", "is", "still", "called" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L321-L324
train
eclipse/paho.mqtt.golang
options.go
SetMessageChannelDepth
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions { o.MessageChannelDepth = s return o }
go
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions { o.MessageChannelDepth = s return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetMessageChannelDepth", "(", "s", "uint", ")", "*", "ClientOptions", "{", "o", ".", "MessageChannelDepth", "=", "s", "\n", "return", "o", "\n", "}" ]
// SetMessageChannelDepth sets the size of the internal queue that holds messages while the // client is temporairily offline, allowing the application to publish when the client is // reconnecting. This setting is only valid if AutoReconnect is set to true, it is otherwise // ignored.
[ "SetMessageChannelDepth", "sets", "the", "size", "of", "the", "internal", "queue", "that", "holds", "messages", "while", "the", "client", "is", "temporairily", "offline", "allowing", "the", "application", "to", "publish", "when", "the", "client", "is", "reconnecting", ".", "This", "setting", "is", "only", "valid", "if", "AutoReconnect", "is", "set", "to", "true", "it", "is", "otherwise", "ignored", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L330-L333
train
eclipse/paho.mqtt.golang
options.go
SetHTTPHeaders
func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions { o.HTTPHeaders = h return o }
go
func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions { o.HTTPHeaders = h return o }
[ "func", "(", "o", "*", "ClientOptions", ")", "SetHTTPHeaders", "(", "h", "http", ".", "Header", ")", "*", "ClientOptions", "{", "o", ".", "HTTPHeaders", "=", "h", "\n", "return", "o", "\n", "}" ]
// SetHTTPHeaders sets the additional HTTP headers that will be sent in the WebSocket // opening handshake.
[ "SetHTTPHeaders", "sets", "the", "additional", "HTTP", "headers", "that", "will", "be", "sent", "in", "the", "WebSocket", "opening", "handshake", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L337-L340
train
eclipse/paho.mqtt.golang
token.go
WaitTimeout
func (b *baseToken) WaitTimeout(d time.Duration) bool { b.m.Lock() defer b.m.Unlock() timer := time.NewTimer(d) select { case <-b.complete: if !timer.Stop() { <-timer.C } return true case <-timer.C: } return false }
go
func (b *baseToken) WaitTimeout(d time.Duration) bool { b.m.Lock() defer b.m.Unlock() timer := time.NewTimer(d) select { case <-b.complete: if !timer.Stop() { <-timer.C } return true case <-timer.C: } return false }
[ "func", "(", "b", "*", "baseToken", ")", "WaitTimeout", "(", "d", "time", ".", "Duration", ")", "bool", "{", "b", ".", "m", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "m", ".", "Unlock", "(", ")", "\n\n", "timer", ":=", "time", ".", "NewTimer", "(", "d", ")", "\n", "select", "{", "case", "<-", "b", ".", "complete", ":", "if", "!", "timer", ".", "Stop", "(", ")", "{", "<-", "timer", ".", "C", "\n", "}", "\n", "return", "true", "\n", "case", "<-", "timer", ".", "C", ":", "}", "\n\n", "return", "false", "\n", "}" ]
// WaitTimeout takes a time.Duration to wait for the flow associated with the // Token to complete, returns true if it returned before the timeout or // returns false if the timeout occurred. In the case of a timeout the Token // does not have an error set in case the caller wishes to wait again
[ "WaitTimeout", "takes", "a", "time", ".", "Duration", "to", "wait", "for", "the", "flow", "associated", "with", "the", "Token", "to", "complete", "returns", "true", "if", "it", "returned", "before", "the", "timeout", "or", "returns", "false", "if", "the", "timeout", "occurred", ".", "In", "the", "case", "of", "a", "timeout", "the", "Token", "does", "not", "have", "an", "error", "set", "in", "case", "the", "caller", "wishes", "to", "wait", "again" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/token.go#L66-L81
train
eclipse/paho.mqtt.golang
token.go
Result
func (s *SubscribeToken) Result() map[string]byte { s.m.RLock() defer s.m.RUnlock() return s.subResult }
go
func (s *SubscribeToken) Result() map[string]byte { s.m.RLock() defer s.m.RUnlock() return s.subResult }
[ "func", "(", "s", "*", "SubscribeToken", ")", "Result", "(", ")", "map", "[", "string", "]", "byte", "{", "s", ".", "m", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "m", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "subResult", "\n", "}" ]
// Result returns a map of topics that were subscribed to along with // the matching return code from the broker. This is either the Qos // value of the subscription or an error code.
[ "Result", "returns", "a", "map", "of", "topics", "that", "were", "subscribed", "to", "along", "with", "the", "matching", "return", "code", "from", "the", "broker", ".", "This", "is", "either", "the", "Qos", "value", "of", "the", "subscription", "or", "an", "error", "code", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/token.go#L168-L172
train
eclipse/paho.mqtt.golang
options_reader.go
Servers
func (r *ClientOptionsReader) Servers() []*url.URL { s := make([]*url.URL, len(r.options.Servers)) for i, u := range r.options.Servers { nu := *u s[i] = &nu } return s }
go
func (r *ClientOptionsReader) Servers() []*url.URL { s := make([]*url.URL, len(r.options.Servers)) for i, u := range r.options.Servers { nu := *u s[i] = &nu } return s }
[ "func", "(", "r", "*", "ClientOptionsReader", ")", "Servers", "(", ")", "[", "]", "*", "url", ".", "URL", "{", "s", ":=", "make", "(", "[", "]", "*", "url", ".", "URL", ",", "len", "(", "r", ".", "options", ".", "Servers", ")", ")", "\n\n", "for", "i", ",", "u", ":=", "range", "r", ".", "options", ".", "Servers", "{", "nu", ":=", "*", "u", "\n", "s", "[", "i", "]", "=", "&", "nu", "\n", "}", "\n\n", "return", "s", "\n", "}" ]
//Servers returns a slice of the servers defined in the clientoptions
[ "Servers", "returns", "a", "slice", "of", "the", "servers", "defined", "in", "the", "clientoptions" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options_reader.go#L30-L39
train
eclipse/paho.mqtt.golang
memstore.go
Open
func (store *MemoryStore) Open() { store.Lock() defer store.Unlock() store.opened = true DEBUG.Println(STR, "memorystore initialized") }
go
func (store *MemoryStore) Open() { store.Lock() defer store.Unlock() store.opened = true DEBUG.Println(STR, "memorystore initialized") }
[ "func", "(", "store", "*", "MemoryStore", ")", "Open", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "store", ".", "opened", "=", "true", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "}" ]
// Open initializes a MemoryStore instance.
[ "Open", "initializes", "a", "MemoryStore", "instance", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L44-L49
train
eclipse/paho.mqtt.golang
memstore.go
Get
func (store *MemoryStore) Get(key string) packets.ControlPacket { store.RLock() defer store.RUnlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return nil } mid := mIDFromKey(key) m := store.messages[key] if m == nil { CRITICAL.Println(STR, "memorystore get: message", mid, "not found") } else { DEBUG.Println(STR, "memorystore get: message", mid, "found") } return m }
go
func (store *MemoryStore) Get(key string) packets.ControlPacket { store.RLock() defer store.RUnlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return nil } mid := mIDFromKey(key) m := store.messages[key] if m == nil { CRITICAL.Println(STR, "memorystore get: message", mid, "not found") } else { DEBUG.Println(STR, "memorystore get: message", mid, "found") } return m }
[ "func", "(", "store", "*", "MemoryStore", ")", "Get", "(", "key", "string", ")", "packets", ".", "ControlPacket", "{", "store", ".", "RLock", "(", ")", "\n", "defer", "store", ".", "RUnlock", "(", ")", "\n", "if", "!", "store", ".", "opened", "{", "ERROR", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "mid", ":=", "mIDFromKey", "(", "key", ")", "\n", "m", ":=", "store", ".", "messages", "[", "key", "]", "\n", "if", "m", "==", "nil", "{", "CRITICAL", ".", "Println", "(", "STR", ",", "\"", "\"", ",", "mid", ",", "\"", "\"", ")", "\n", "}", "else", "{", "DEBUG", ".", "Println", "(", "STR", ",", "\"", "\"", ",", "mid", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Get takes a key and looks in the store for a matching Message // returning either the Message pointer or nil.
[ "Get", "takes", "a", "key", "and", "looks", "in", "the", "store", "for", "a", "matching", "Message", "returning", "either", "the", "Message", "pointer", "or", "nil", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L65-L80
train
eclipse/paho.mqtt.golang
memstore.go
Del
func (store *MemoryStore) Del(key string) { store.Lock() defer store.Unlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return } mid := mIDFromKey(key) m := store.messages[key] if m == nil { WARN.Println(STR, "memorystore del: message", mid, "not found") } else { delete(store.messages, key) DEBUG.Println(STR, "memorystore del: message", mid, "was deleted") } }
go
func (store *MemoryStore) Del(key string) { store.Lock() defer store.Unlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return } mid := mIDFromKey(key) m := store.messages[key] if m == nil { WARN.Println(STR, "memorystore del: message", mid, "not found") } else { delete(store.messages, key) DEBUG.Println(STR, "memorystore del: message", mid, "was deleted") } }
[ "func", "(", "store", "*", "MemoryStore", ")", "Del", "(", "key", "string", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "if", "!", "store", ".", "opened", "{", "ERROR", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "mid", ":=", "mIDFromKey", "(", "key", ")", "\n", "m", ":=", "store", ".", "messages", "[", "key", "]", "\n", "if", "m", "==", "nil", "{", "WARN", ".", "Println", "(", "STR", ",", "\"", "\"", ",", "mid", ",", "\"", "\"", ")", "\n", "}", "else", "{", "delete", "(", "store", ".", "messages", ",", "key", ")", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "\"", "\"", ",", "mid", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Del takes a key, searches the MemoryStore and if the key is found // deletes the Message pointer associated with it.
[ "Del", "takes", "a", "key", "searches", "the", "MemoryStore", "and", "if", "the", "key", "is", "found", "deletes", "the", "Message", "pointer", "associated", "with", "it", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L100-L115
train
eclipse/paho.mqtt.golang
client.go
AddRoute
func (c *client) AddRoute(topic string, callback MessageHandler) { if callback != nil { c.msgRouter.addRoute(topic, callback) } }
go
func (c *client) AddRoute(topic string, callback MessageHandler) { if callback != nil { c.msgRouter.addRoute(topic, callback) } }
[ "func", "(", "c", "*", "client", ")", "AddRoute", "(", "topic", "string", ",", "callback", "MessageHandler", ")", "{", "if", "callback", "!=", "nil", "{", "c", ".", "msgRouter", ".", "addRoute", "(", "topic", ",", "callback", ")", "\n", "}", "\n", "}" ]
// AddRoute allows you to add a handler for messages on a specific topic // without making a subscription. For example having a different handler // for parts of a wildcard subscription
[ "AddRoute", "allows", "you", "to", "add", "a", "handler", "for", "messages", "on", "a", "specific", "topic", "without", "making", "a", "subscription", ".", "For", "example", "having", "a", "different", "handler", "for", "parts", "of", "a", "wildcard", "subscription" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L152-L156
train
eclipse/paho.mqtt.golang
client.go
IsConnectionOpen
func (c *client) IsConnectionOpen() bool { c.RLock() defer c.RUnlock() status := atomic.LoadUint32(&c.status) switch { case status == connected: return true default: return false } }
go
func (c *client) IsConnectionOpen() bool { c.RLock() defer c.RUnlock() status := atomic.LoadUint32(&c.status) switch { case status == connected: return true default: return false } }
[ "func", "(", "c", "*", "client", ")", "IsConnectionOpen", "(", ")", "bool", "{", "c", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "RUnlock", "(", ")", "\n", "status", ":=", "atomic", ".", "LoadUint32", "(", "&", "c", ".", "status", ")", "\n", "switch", "{", "case", "status", "==", "connected", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsConnectionOpen return a bool signifying whether the client has an active // connection to mqtt broker, i.e not in disconnected or reconnect mode
[ "IsConnectionOpen", "return", "a", "bool", "signifying", "whether", "the", "client", "has", "an", "active", "connection", "to", "mqtt", "broker", "i", ".", "e", "not", "in", "disconnected", "or", "reconnect", "mode" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L176-L186
train
eclipse/paho.mqtt.golang
client.go
Publish
func (c *client) Publish(topic string, qos byte, retained bool, payload interface{}) Token { token := newToken(packets.Publish).(*PublishToken) DEBUG.Println(CLI, "enter Publish") switch { case !c.IsConnected(): token.setError(ErrNotConnected) return token case c.connectionStatus() == reconnecting && qos == 0: token.flowComplete() return token } pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) pub.Qos = qos pub.TopicName = topic pub.Retain = retained switch payload.(type) { case string: pub.Payload = []byte(payload.(string)) case []byte: pub.Payload = payload.([]byte) default: token.setError(fmt.Errorf("Unknown payload type")) return token } if pub.Qos != 0 && pub.MessageID == 0 { pub.MessageID = c.getID(token) token.messageID = pub.MessageID } persistOutbound(c.persist, pub) if c.connectionStatus() == reconnecting { DEBUG.Println(CLI, "storing publish message (reconnecting), topic:", topic) } else { DEBUG.Println(CLI, "sending publish message, topic:", topic) c.obound <- &PacketAndToken{p: pub, t: token} } return token }
go
func (c *client) Publish(topic string, qos byte, retained bool, payload interface{}) Token { token := newToken(packets.Publish).(*PublishToken) DEBUG.Println(CLI, "enter Publish") switch { case !c.IsConnected(): token.setError(ErrNotConnected) return token case c.connectionStatus() == reconnecting && qos == 0: token.flowComplete() return token } pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) pub.Qos = qos pub.TopicName = topic pub.Retain = retained switch payload.(type) { case string: pub.Payload = []byte(payload.(string)) case []byte: pub.Payload = payload.([]byte) default: token.setError(fmt.Errorf("Unknown payload type")) return token } if pub.Qos != 0 && pub.MessageID == 0 { pub.MessageID = c.getID(token) token.messageID = pub.MessageID } persistOutbound(c.persist, pub) if c.connectionStatus() == reconnecting { DEBUG.Println(CLI, "storing publish message (reconnecting), topic:", topic) } else { DEBUG.Println(CLI, "sending publish message, topic:", topic) c.obound <- &PacketAndToken{p: pub, t: token} } return token }
[ "func", "(", "c", "*", "client", ")", "Publish", "(", "topic", "string", ",", "qos", "byte", ",", "retained", "bool", ",", "payload", "interface", "{", "}", ")", "Token", "{", "token", ":=", "newToken", "(", "packets", ".", "Publish", ")", ".", "(", "*", "PublishToken", ")", "\n", "DEBUG", ".", "Println", "(", "CLI", ",", "\"", "\"", ")", "\n", "switch", "{", "case", "!", "c", ".", "IsConnected", "(", ")", ":", "token", ".", "setError", "(", "ErrNotConnected", ")", "\n", "return", "token", "\n", "case", "c", ".", "connectionStatus", "(", ")", "==", "reconnecting", "&&", "qos", "==", "0", ":", "token", ".", "flowComplete", "(", ")", "\n", "return", "token", "\n", "}", "\n", "pub", ":=", "packets", ".", "NewControlPacket", "(", "packets", ".", "Publish", ")", ".", "(", "*", "packets", ".", "PublishPacket", ")", "\n", "pub", ".", "Qos", "=", "qos", "\n", "pub", ".", "TopicName", "=", "topic", "\n", "pub", ".", "Retain", "=", "retained", "\n", "switch", "payload", ".", "(", "type", ")", "{", "case", "string", ":", "pub", ".", "Payload", "=", "[", "]", "byte", "(", "payload", ".", "(", "string", ")", ")", "\n", "case", "[", "]", "byte", ":", "pub", ".", "Payload", "=", "payload", ".", "(", "[", "]", "byte", ")", "\n", "default", ":", "token", ".", "setError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "return", "token", "\n", "}", "\n\n", "if", "pub", ".", "Qos", "!=", "0", "&&", "pub", ".", "MessageID", "==", "0", "{", "pub", ".", "MessageID", "=", "c", ".", "getID", "(", "token", ")", "\n", "token", ".", "messageID", "=", "pub", ".", "MessageID", "\n", "}", "\n", "persistOutbound", "(", "c", ".", "persist", ",", "pub", ")", "\n", "if", "c", ".", "connectionStatus", "(", ")", "==", "reconnecting", "{", "DEBUG", ".", "Println", "(", "CLI", ",", "\"", "\"", ",", "topic", ")", "\n", "}", "else", "{", "DEBUG", ".", "Println", "(", "CLI", ",", "\"", "\"", ",", "topic", ")", "\n", "c", ".", "obound", "<-", "&", "PacketAndToken", "{", "p", ":", "pub", ",", "t", ":", "token", "}", "\n", "}", "\n", "return", "token", "\n", "}" ]
// Publish will publish a message with the specified QoS and content // to the specified topic. // Returns a token to track delivery of the message to the broker
[ "Publish", "will", "publish", "a", "message", "with", "the", "specified", "QoS", "and", "content", "to", "the", "specified", "topic", ".", "Returns", "a", "token", "to", "track", "delivery", "of", "the", "message", "to", "the", "broker" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L568-L605
train
eclipse/paho.mqtt.golang
client.go
resume
func (c *client) resume(subscription bool) { storedKeys := c.persist.All() for _, key := range storedKeys { packet := c.persist.Get(key) if packet == nil { continue } details := packet.Details() if isKeyOutbound(key) { switch packet.(type) { case *packets.SubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending subscribe (%d)", details.MessageID)) token := newToken(packets.Subscribe).(*SubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.UnsubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending unsubscribe (%d)", details.MessageID)) token := newToken(packets.Unsubscribe).(*UnsubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.PubrelPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending pubrel (%d)", details.MessageID)) select { case c.oboundP <- &PacketAndToken{p: packet, t: nil}: case <-c.stop: } case *packets.PublishPacket: token := newToken(packets.Publish).(*PublishToken) token.messageID = details.MessageID c.claimID(token, details.MessageID) DEBUG.Println(STR, fmt.Sprintf("loaded pending publish (%d)", details.MessageID)) DEBUG.Println(STR, details) c.obound <- &PacketAndToken{p: packet, t: token} default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } else { switch packet.(type) { case *packets.PubrelPacket, *packets.PublishPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending incomming (%d)", details.MessageID)) select { case c.ibound <- packet: case <-c.stop: } default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } } }
go
func (c *client) resume(subscription bool) { storedKeys := c.persist.All() for _, key := range storedKeys { packet := c.persist.Get(key) if packet == nil { continue } details := packet.Details() if isKeyOutbound(key) { switch packet.(type) { case *packets.SubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending subscribe (%d)", details.MessageID)) token := newToken(packets.Subscribe).(*SubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.UnsubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending unsubscribe (%d)", details.MessageID)) token := newToken(packets.Unsubscribe).(*UnsubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.PubrelPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending pubrel (%d)", details.MessageID)) select { case c.oboundP <- &PacketAndToken{p: packet, t: nil}: case <-c.stop: } case *packets.PublishPacket: token := newToken(packets.Publish).(*PublishToken) token.messageID = details.MessageID c.claimID(token, details.MessageID) DEBUG.Println(STR, fmt.Sprintf("loaded pending publish (%d)", details.MessageID)) DEBUG.Println(STR, details) c.obound <- &PacketAndToken{p: packet, t: token} default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } else { switch packet.(type) { case *packets.PubrelPacket, *packets.PublishPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending incomming (%d)", details.MessageID)) select { case c.ibound <- packet: case <-c.stop: } default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } } }
[ "func", "(", "c", "*", "client", ")", "resume", "(", "subscription", "bool", ")", "{", "storedKeys", ":=", "c", ".", "persist", ".", "All", "(", ")", "\n", "for", "_", ",", "key", ":=", "range", "storedKeys", "{", "packet", ":=", "c", ".", "persist", ".", "Get", "(", "key", ")", "\n", "if", "packet", "==", "nil", "{", "continue", "\n", "}", "\n", "details", ":=", "packet", ".", "Details", "(", ")", "\n", "if", "isKeyOutbound", "(", "key", ")", "{", "switch", "packet", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "SubscribePacket", ":", "if", "subscription", "{", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "details", ".", "MessageID", ")", ")", "\n", "token", ":=", "newToken", "(", "packets", ".", "Subscribe", ")", ".", "(", "*", "SubscribeToken", ")", "\n", "c", ".", "oboundP", "<-", "&", "PacketAndToken", "{", "p", ":", "packet", ",", "t", ":", "token", "}", "\n", "}", "\n", "case", "*", "packets", ".", "UnsubscribePacket", ":", "if", "subscription", "{", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "details", ".", "MessageID", ")", ")", "\n", "token", ":=", "newToken", "(", "packets", ".", "Unsubscribe", ")", ".", "(", "*", "UnsubscribeToken", ")", "\n", "c", ".", "oboundP", "<-", "&", "PacketAndToken", "{", "p", ":", "packet", ",", "t", ":", "token", "}", "\n", "}", "\n", "case", "*", "packets", ".", "PubrelPacket", ":", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "details", ".", "MessageID", ")", ")", "\n", "select", "{", "case", "c", ".", "oboundP", "<-", "&", "PacketAndToken", "{", "p", ":", "packet", ",", "t", ":", "nil", "}", ":", "case", "<-", "c", ".", "stop", ":", "}", "\n", "case", "*", "packets", ".", "PublishPacket", ":", "token", ":=", "newToken", "(", "packets", ".", "Publish", ")", ".", "(", "*", "PublishToken", ")", "\n", "token", ".", "messageID", "=", "details", ".", "MessageID", "\n", "c", ".", "claimID", "(", "token", ",", "details", ".", "MessageID", ")", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "details", ".", "MessageID", ")", ")", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "details", ")", "\n", "c", ".", "obound", "<-", "&", "PacketAndToken", "{", "p", ":", "packet", ",", "t", ":", "token", "}", "\n", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "c", ".", "persist", ".", "Del", "(", "key", ")", "\n", "}", "\n", "}", "else", "{", "switch", "packet", ".", "(", "type", ")", "{", "case", "*", "packets", ".", "PubrelPacket", ",", "*", "packets", ".", "PublishPacket", ":", "DEBUG", ".", "Println", "(", "STR", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "details", ".", "MessageID", ")", ")", "\n", "select", "{", "case", "c", ".", "ibound", "<-", "packet", ":", "case", "<-", "c", ".", "stop", ":", "}", "\n", "default", ":", "ERROR", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "c", ".", "persist", ".", "Del", "(", "key", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Load all stored messages and resend them // Call this to ensure QOS > 1,2 even after an application crash
[ "Load", "all", "stored", "messages", "and", "resend", "them", "Call", "this", "to", "ensure", "QOS", ">", "1", "2", "even", "after", "an", "application", "crash" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L669-L723
train
eclipse/paho.mqtt.golang
client.go
OptionsReader
func (c *client) OptionsReader() ClientOptionsReader { r := ClientOptionsReader{options: &c.options} return r }
go
func (c *client) OptionsReader() ClientOptionsReader { r := ClientOptionsReader{options: &c.options} return r }
[ "func", "(", "c", "*", "client", ")", "OptionsReader", "(", ")", "ClientOptionsReader", "{", "r", ":=", "ClientOptionsReader", "{", "options", ":", "&", "c", ".", "options", "}", "\n", "return", "r", "\n", "}" ]
// OptionsReader returns a ClientOptionsReader which is a copy of the clientoptions // in use by the client.
[ "OptionsReader", "returns", "a", "ClientOptionsReader", "which", "is", "a", "copy", "of", "the", "clientoptions", "in", "use", "by", "the", "client", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L750-L753
train
eclipse/paho.mqtt.golang
packets/publish.go
Copy
func (p *PublishPacket) Copy() *PublishPacket { newP := NewControlPacket(Publish).(*PublishPacket) newP.TopicName = p.TopicName newP.Payload = p.Payload return newP }
go
func (p *PublishPacket) Copy() *PublishPacket { newP := NewControlPacket(Publish).(*PublishPacket) newP.TopicName = p.TopicName newP.Payload = p.Payload return newP }
[ "func", "(", "p", "*", "PublishPacket", ")", "Copy", "(", ")", "*", "PublishPacket", "{", "newP", ":=", "NewControlPacket", "(", "Publish", ")", ".", "(", "*", "PublishPacket", ")", "\n", "newP", ".", "TopicName", "=", "p", ".", "TopicName", "\n", "newP", ".", "Payload", "=", "p", ".", "Payload", "\n\n", "return", "newP", "\n", "}" ]
//Copy creates a new PublishPacket with the same topic and payload //but an empty fixed header, useful for when you want to deliver //a message with different properties such as Qos but the same //content
[ "Copy", "creates", "a", "new", "PublishPacket", "with", "the", "same", "topic", "and", "payload", "but", "an", "empty", "fixed", "header", "useful", "for", "when", "you", "want", "to", "deliver", "a", "message", "with", "different", "properties", "such", "as", "Qos", "but", "the", "same", "content" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/publish.go#L76-L82
train
eclipse/paho.mqtt.golang
filestore.go
NewFileStore
func NewFileStore(directory string) *FileStore { store := &FileStore{ directory: directory, opened: false, } return store }
go
func NewFileStore(directory string) *FileStore { store := &FileStore{ directory: directory, opened: false, } return store }
[ "func", "NewFileStore", "(", "directory", "string", ")", "*", "FileStore", "{", "store", ":=", "&", "FileStore", "{", "directory", ":", "directory", ",", "opened", ":", "false", ",", "}", "\n", "return", "store", "\n", "}" ]
// NewFileStore will create a new FileStore which stores its messages in the // directory provided.
[ "NewFileStore", "will", "create", "a", "new", "FileStore", "which", "stores", "its", "messages", "in", "the", "directory", "provided", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L46-L52
train
eclipse/paho.mqtt.golang
filestore.go
Open
func (store *FileStore) Open() { store.Lock() defer store.Unlock() // if no store directory was specified in ClientOpts, by default use the // current working directory if store.directory == "" { store.directory, _ = os.Getwd() } // if store dir exists, great, otherwise, create it if !exists(store.directory) { perms := os.FileMode(0770) merr := os.MkdirAll(store.directory, perms) chkerr(merr) } store.opened = true DEBUG.Println(STR, "store is opened at", store.directory) }
go
func (store *FileStore) Open() { store.Lock() defer store.Unlock() // if no store directory was specified in ClientOpts, by default use the // current working directory if store.directory == "" { store.directory, _ = os.Getwd() } // if store dir exists, great, otherwise, create it if !exists(store.directory) { perms := os.FileMode(0770) merr := os.MkdirAll(store.directory, perms) chkerr(merr) } store.opened = true DEBUG.Println(STR, "store is opened at", store.directory) }
[ "func", "(", "store", "*", "FileStore", ")", "Open", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "// if no store directory was specified in ClientOpts, by default use the", "// current working directory", "if", "store", ".", "directory", "==", "\"", "\"", "{", "store", ".", "directory", ",", "_", "=", "os", ".", "Getwd", "(", ")", "\n", "}", "\n\n", "// if store dir exists, great, otherwise, create it", "if", "!", "exists", "(", "store", ".", "directory", ")", "{", "perms", ":=", "os", ".", "FileMode", "(", "0770", ")", "\n", "merr", ":=", "os", ".", "MkdirAll", "(", "store", ".", "directory", ",", "perms", ")", "\n", "chkerr", "(", "merr", ")", "\n", "}", "\n", "store", ".", "opened", "=", "true", "\n", "DEBUG", ".", "Println", "(", "STR", ",", "\"", "\"", ",", "store", ".", "directory", ")", "\n", "}" ]
// Open will allow the FileStore to be used.
[ "Open", "will", "allow", "the", "FileStore", "to", "be", "used", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L55-L72
train
eclipse/paho.mqtt.golang
filestore.go
All
func (store *FileStore) All() []string { store.RLock() defer store.RUnlock() return store.all() }
go
func (store *FileStore) All() []string { store.RLock() defer store.RUnlock() return store.all() }
[ "func", "(", "store", "*", "FileStore", ")", "All", "(", ")", "[", "]", "string", "{", "store", ".", "RLock", "(", ")", "\n", "defer", "store", ".", "RUnlock", "(", ")", "\n", "return", "store", ".", "all", "(", ")", "\n", "}" ]
// All will provide a list of all of the keys associated with messages // currenly residing in the FileStore.
[ "All", "will", "provide", "a", "list", "of", "all", "of", "the", "keys", "associated", "with", "messages", "currenly", "residing", "in", "the", "FileStore", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L128-L132
train
eclipse/paho.mqtt.golang
filestore.go
Del
func (store *FileStore) Del(key string) { store.Lock() defer store.Unlock() store.del(key) }
go
func (store *FileStore) Del(key string) { store.Lock() defer store.Unlock() store.del(key) }
[ "func", "(", "store", "*", "FileStore", ")", "Del", "(", "key", "string", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "store", ".", "del", "(", "key", ")", "\n", "}" ]
// Del will remove the persisted message associated with the provided // key from the FileStore.
[ "Del", "will", "remove", "the", "persisted", "message", "associated", "with", "the", "provided", "key", "from", "the", "FileStore", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L136-L140
train
eclipse/paho.mqtt.golang
filestore.go
Reset
func (store *FileStore) Reset() { store.Lock() defer store.Unlock() WARN.Println(STR, "FileStore Reset") for _, key := range store.all() { store.del(key) } }
go
func (store *FileStore) Reset() { store.Lock() defer store.Unlock() WARN.Println(STR, "FileStore Reset") for _, key := range store.all() { store.del(key) } }
[ "func", "(", "store", "*", "FileStore", ")", "Reset", "(", ")", "{", "store", ".", "Lock", "(", ")", "\n", "defer", "store", ".", "Unlock", "(", ")", "\n", "WARN", ".", "Println", "(", "STR", ",", "\"", "\"", ")", "\n", "for", "_", ",", "key", ":=", "range", "store", ".", "all", "(", ")", "{", "store", ".", "del", "(", "key", ")", "\n", "}", "\n", "}" ]
// Reset will remove all persisted messages from the FileStore.
[ "Reset", "will", "remove", "all", "persisted", "messages", "from", "the", "FileStore", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L143-L150
train
eclipse/paho.mqtt.golang
router.go
newRouter
func newRouter() (*router, chan bool) { router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket), stop: make(chan bool)} stop := router.stop return router, stop }
go
func newRouter() (*router, chan bool) { router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket), stop: make(chan bool)} stop := router.stop return router, stop }
[ "func", "newRouter", "(", ")", "(", "*", "router", ",", "chan", "bool", ")", "{", "router", ":=", "&", "router", "{", "routes", ":", "list", ".", "New", "(", ")", ",", "messages", ":", "make", "(", "chan", "*", "packets", ".", "PublishPacket", ")", ",", "stop", ":", "make", "(", "chan", "bool", ")", "}", "\n", "stop", ":=", "router", ".", "stop", "\n", "return", "router", ",", "stop", "\n", "}" ]
// newRouter returns a new instance of a Router and channel which can be used to tell the Router // to stop
[ "newRouter", "returns", "a", "new", "instance", "of", "a", "Router", "and", "channel", "which", "can", "be", "used", "to", "tell", "the", "Router", "to", "stop" ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L95-L99
train
eclipse/paho.mqtt.golang
router.go
addRoute
func (r *router) addRoute(topic string, callback MessageHandler) { r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r := e.Value.(*route) r.callback = callback return } } r.routes.PushBack(&route{topic: topic, callback: callback}) }
go
func (r *router) addRoute(topic string, callback MessageHandler) { r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r := e.Value.(*route) r.callback = callback return } } r.routes.PushBack(&route{topic: topic, callback: callback}) }
[ "func", "(", "r", "*", "router", ")", "addRoute", "(", "topic", "string", ",", "callback", "MessageHandler", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "for", "e", ":=", "r", ".", "routes", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "if", "e", ".", "Value", ".", "(", "*", "route", ")", ".", "match", "(", "topic", ")", "{", "r", ":=", "e", ".", "Value", ".", "(", "*", "route", ")", "\n", "r", ".", "callback", "=", "callback", "\n", "return", "\n", "}", "\n", "}", "\n", "r", ".", "routes", ".", "PushBack", "(", "&", "route", "{", "topic", ":", "topic", ",", "callback", ":", "callback", "}", ")", "\n", "}" ]
// addRoute takes a topic string and MessageHandler callback. It looks in the current list of // routes to see if there is already a matching Route. If there is it replaces the current // callback with the new one. If not it add a new entry to the list of Routes.
[ "addRoute", "takes", "a", "topic", "string", "and", "MessageHandler", "callback", ".", "It", "looks", "in", "the", "current", "list", "of", "routes", "to", "see", "if", "there", "is", "already", "a", "matching", "Route", ".", "If", "there", "is", "it", "replaces", "the", "current", "callback", "with", "the", "new", "one", ".", "If", "not", "it", "add", "a", "new", "entry", "to", "the", "list", "of", "Routes", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L104-L115
train
eclipse/paho.mqtt.golang
router.go
deleteRoute
func (r *router) deleteRoute(topic string) { r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r.routes.Remove(e) return } } }
go
func (r *router) deleteRoute(topic string) { r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r.routes.Remove(e) return } } }
[ "func", "(", "r", "*", "router", ")", "deleteRoute", "(", "topic", "string", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "for", "e", ":=", "r", ".", "routes", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "if", "e", ".", "Value", ".", "(", "*", "route", ")", ".", "match", "(", "topic", ")", "{", "r", ".", "routes", ".", "Remove", "(", "e", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// deleteRoute takes a route string, looks for a matching Route in the list of Routes. If // found it removes the Route from the list.
[ "deleteRoute", "takes", "a", "route", "string", "looks", "for", "a", "matching", "Route", "in", "the", "list", "of", "Routes", ".", "If", "found", "it", "removes", "the", "Route", "from", "the", "list", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L119-L128
train
eclipse/paho.mqtt.golang
router.go
setDefaultHandler
func (r *router) setDefaultHandler(handler MessageHandler) { r.Lock() defer r.Unlock() r.defaultHandler = handler }
go
func (r *router) setDefaultHandler(handler MessageHandler) { r.Lock() defer r.Unlock() r.defaultHandler = handler }
[ "func", "(", "r", "*", "router", ")", "setDefaultHandler", "(", "handler", "MessageHandler", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "r", ".", "defaultHandler", "=", "handler", "\n", "}" ]
// setDefaultHandler assigns a default callback that will be called if no matching Route // is found for an incoming Publish.
[ "setDefaultHandler", "assigns", "a", "default", "callback", "that", "will", "be", "called", "if", "no", "matching", "Route", "is", "found", "for", "an", "incoming", "Publish", "." ]
adca289fdcf8c883800aafa545bc263452290bae
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L132-L136
train
nats-io/go-nats
enc.go
NewEncodedConn
func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error) { if c == nil { return nil, errors.New("nats: Nil Connection") } if c.IsClosed() { return nil, ErrConnectionClosed } ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)} if ec.Enc == nil { return nil, fmt.Errorf("no encoder registered for '%s'", encType) } return ec, nil }
go
func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error) { if c == nil { return nil, errors.New("nats: Nil Connection") } if c.IsClosed() { return nil, ErrConnectionClosed } ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)} if ec.Enc == nil { return nil, fmt.Errorf("no encoder registered for '%s'", encType) } return ec, nil }
[ "func", "NewEncodedConn", "(", "c", "*", "Conn", ",", "encType", "string", ")", "(", "*", "EncodedConn", ",", "error", ")", "{", "if", "c", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "IsClosed", "(", ")", "{", "return", "nil", ",", "ErrConnectionClosed", "\n", "}", "\n", "ec", ":=", "&", "EncodedConn", "{", "Conn", ":", "c", ",", "Enc", ":", "EncoderForType", "(", "encType", ")", "}", "\n", "if", "ec", ".", "Enc", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "encType", ")", "\n", "}", "\n", "return", "ec", ",", "nil", "\n", "}" ]
// NewEncodedConn will wrap an existing Connection and utilize the appropriate registered // encoder.
[ "NewEncodedConn", "will", "wrap", "an", "existing", "Connection", "and", "utilize", "the", "appropriate", "registered", "encoder", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L61-L73
train
nats-io/go-nats
enc.go
RegisterEncoder
func RegisterEncoder(encType string, enc Encoder) { encLock.Lock() defer encLock.Unlock() encMap[encType] = enc }
go
func RegisterEncoder(encType string, enc Encoder) { encLock.Lock() defer encLock.Unlock() encMap[encType] = enc }
[ "func", "RegisterEncoder", "(", "encType", "string", ",", "enc", "Encoder", ")", "{", "encLock", ".", "Lock", "(", ")", "\n", "defer", "encLock", ".", "Unlock", "(", ")", "\n", "encMap", "[", "encType", "]", "=", "enc", "\n", "}" ]
// RegisterEncoder will register the encType with the given Encoder. Useful for customization.
[ "RegisterEncoder", "will", "register", "the", "encType", "with", "the", "given", "Encoder", ".", "Useful", "for", "customization", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L76-L80
train
nats-io/go-nats
enc.go
EncoderForType
func EncoderForType(encType string) Encoder { encLock.Lock() defer encLock.Unlock() return encMap[encType] }
go
func EncoderForType(encType string) Encoder { encLock.Lock() defer encLock.Unlock() return encMap[encType] }
[ "func", "EncoderForType", "(", "encType", "string", ")", "Encoder", "{", "encLock", ".", "Lock", "(", ")", "\n", "defer", "encLock", ".", "Unlock", "(", ")", "\n", "return", "encMap", "[", "encType", "]", "\n", "}" ]
// EncoderForType will return the registered Encoder for the encType.
[ "EncoderForType", "will", "return", "the", "registered", "Encoder", "for", "the", "encType", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L83-L87
train
nats-io/go-nats
enc.go
Publish
func (c *EncodedConn) Publish(subject string, v interface{}) error { b, err := c.Enc.Encode(subject, v) if err != nil { return err } return c.Conn.publish(subject, _EMPTY_, b) }
go
func (c *EncodedConn) Publish(subject string, v interface{}) error { b, err := c.Enc.Encode(subject, v) if err != nil { return err } return c.Conn.publish(subject, _EMPTY_, b) }
[ "func", "(", "c", "*", "EncodedConn", ")", "Publish", "(", "subject", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "b", ",", "err", ":=", "c", ".", "Enc", ".", "Encode", "(", "subject", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "Conn", ".", "publish", "(", "subject", ",", "_EMPTY_", ",", "b", ")", "\n", "}" ]
// Publish publishes the data argument to the given subject. The data argument // will be encoded using the associated encoder.
[ "Publish", "publishes", "the", "data", "argument", "to", "the", "given", "subject", ".", "The", "data", "argument", "will", "be", "encoded", "using", "the", "associated", "encoder", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L91-L97
train
nats-io/go-nats
enc.go
argInfo
func argInfo(cb Handler) (reflect.Type, int) { cbType := reflect.TypeOf(cb) if cbType.Kind() != reflect.Func { panic("nats: Handler needs to be a func") } numArgs := cbType.NumIn() if numArgs == 0 { return nil, numArgs } return cbType.In(numArgs - 1), numArgs }
go
func argInfo(cb Handler) (reflect.Type, int) { cbType := reflect.TypeOf(cb) if cbType.Kind() != reflect.Func { panic("nats: Handler needs to be a func") } numArgs := cbType.NumIn() if numArgs == 0 { return nil, numArgs } return cbType.In(numArgs - 1), numArgs }
[ "func", "argInfo", "(", "cb", "Handler", ")", "(", "reflect", ".", "Type", ",", "int", ")", "{", "cbType", ":=", "reflect", ".", "TypeOf", "(", "cb", ")", "\n", "if", "cbType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Func", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "numArgs", ":=", "cbType", ".", "NumIn", "(", ")", "\n", "if", "numArgs", "==", "0", "{", "return", "nil", ",", "numArgs", "\n", "}", "\n", "return", "cbType", ".", "In", "(", "numArgs", "-", "1", ")", ",", "numArgs", "\n", "}" ]
// Dissect the cb Handler's signature
[ "Dissect", "the", "cb", "Handler", "s", "signature" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L156-L166
train
nats-io/go-nats
enc.go
Subscribe
func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error) { return c.subscribe(subject, _EMPTY_, cb) }
go
func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error) { return c.subscribe(subject, _EMPTY_, cb) }
[ "func", "(", "c", "*", "EncodedConn", ")", "Subscribe", "(", "subject", "string", ",", "cb", "Handler", ")", "(", "*", "Subscription", ",", "error", ")", "{", "return", "c", ".", "subscribe", "(", "subject", ",", "_EMPTY_", ",", "cb", ")", "\n", "}" ]
// Subscribe will create a subscription on the given subject and process incoming // messages using the specified Handler. The Handler should be a func that matches // a signature from the description of Handler from above.
[ "Subscribe", "will", "create", "a", "subscription", "on", "the", "given", "subject", "and", "process", "incoming", "messages", "using", "the", "specified", "Handler", ".", "The", "Handler", "should", "be", "a", "func", "that", "matches", "a", "signature", "from", "the", "description", "of", "Handler", "from", "above", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L173-L175
train
nats-io/go-nats
enc.go
QueueSubscribe
func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error) { return c.subscribe(subject, queue, cb) }
go
func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error) { return c.subscribe(subject, queue, cb) }
[ "func", "(", "c", "*", "EncodedConn", ")", "QueueSubscribe", "(", "subject", ",", "queue", "string", ",", "cb", "Handler", ")", "(", "*", "Subscription", ",", "error", ")", "{", "return", "c", ".", "subscribe", "(", "subject", ",", "queue", ",", "cb", ")", "\n", "}" ]
// QueueSubscribe will create a queue subscription on the given subject and process // incoming messages using the specified Handler. The Handler should be a func that // matches a signature from the description of Handler from above.
[ "QueueSubscribe", "will", "create", "a", "queue", "subscription", "on", "the", "given", "subject", "and", "process", "incoming", "messages", "using", "the", "specified", "Handler", ".", "The", "Handler", "should", "be", "a", "func", "that", "matches", "a", "signature", "from", "the", "description", "of", "Handler", "from", "above", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L180-L182
train
nats-io/go-nats
enc.go
subscribe
func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error) { if cb == nil { return nil, errors.New("nats: Handler required for EncodedConn Subscription") } argType, numArgs := argInfo(cb) if argType == nil { return nil, errors.New("nats: Handler requires at least one argument") } cbValue := reflect.ValueOf(cb) wantsRaw := (argType == emptyMsgType) natsCB := func(m *Msg) { var oV []reflect.Value if wantsRaw { oV = []reflect.Value{reflect.ValueOf(m)} } else { var oPtr reflect.Value if argType.Kind() != reflect.Ptr { oPtr = reflect.New(argType) } else { oPtr = reflect.New(argType.Elem()) } if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { if c.Conn.Opts.AsyncErrorCB != nil { c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error())) }) } return } if argType.Kind() != reflect.Ptr { oPtr = reflect.Indirect(oPtr) } // Callback Arity switch numArgs { case 1: oV = []reflect.Value{oPtr} case 2: subV := reflect.ValueOf(m.Subject) oV = []reflect.Value{subV, oPtr} case 3: subV := reflect.ValueOf(m.Subject) replyV := reflect.ValueOf(m.Reply) oV = []reflect.Value{subV, replyV, oPtr} } } cbValue.Call(oV) } return c.Conn.subscribe(subject, queue, natsCB, nil, false) }
go
func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error) { if cb == nil { return nil, errors.New("nats: Handler required for EncodedConn Subscription") } argType, numArgs := argInfo(cb) if argType == nil { return nil, errors.New("nats: Handler requires at least one argument") } cbValue := reflect.ValueOf(cb) wantsRaw := (argType == emptyMsgType) natsCB := func(m *Msg) { var oV []reflect.Value if wantsRaw { oV = []reflect.Value{reflect.ValueOf(m)} } else { var oPtr reflect.Value if argType.Kind() != reflect.Ptr { oPtr = reflect.New(argType) } else { oPtr = reflect.New(argType.Elem()) } if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { if c.Conn.Opts.AsyncErrorCB != nil { c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error())) }) } return } if argType.Kind() != reflect.Ptr { oPtr = reflect.Indirect(oPtr) } // Callback Arity switch numArgs { case 1: oV = []reflect.Value{oPtr} case 2: subV := reflect.ValueOf(m.Subject) oV = []reflect.Value{subV, oPtr} case 3: subV := reflect.ValueOf(m.Subject) replyV := reflect.ValueOf(m.Reply) oV = []reflect.Value{subV, replyV, oPtr} } } cbValue.Call(oV) } return c.Conn.subscribe(subject, queue, natsCB, nil, false) }
[ "func", "(", "c", "*", "EncodedConn", ")", "subscribe", "(", "subject", ",", "queue", "string", ",", "cb", "Handler", ")", "(", "*", "Subscription", ",", "error", ")", "{", "if", "cb", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "argType", ",", "numArgs", ":=", "argInfo", "(", "cb", ")", "\n", "if", "argType", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "cbValue", ":=", "reflect", ".", "ValueOf", "(", "cb", ")", "\n", "wantsRaw", ":=", "(", "argType", "==", "emptyMsgType", ")", "\n\n", "natsCB", ":=", "func", "(", "m", "*", "Msg", ")", "{", "var", "oV", "[", "]", "reflect", ".", "Value", "\n", "if", "wantsRaw", "{", "oV", "=", "[", "]", "reflect", ".", "Value", "{", "reflect", ".", "ValueOf", "(", "m", ")", "}", "\n", "}", "else", "{", "var", "oPtr", "reflect", ".", "Value", "\n", "if", "argType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "oPtr", "=", "reflect", ".", "New", "(", "argType", ")", "\n", "}", "else", "{", "oPtr", "=", "reflect", ".", "New", "(", "argType", ".", "Elem", "(", ")", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "Enc", ".", "Decode", "(", "m", ".", "Subject", ",", "m", ".", "Data", ",", "oPtr", ".", "Interface", "(", ")", ")", ";", "err", "!=", "nil", "{", "if", "c", ".", "Conn", ".", "Opts", ".", "AsyncErrorCB", "!=", "nil", "{", "c", ".", "Conn", ".", "ach", ".", "push", "(", "func", "(", ")", "{", "c", ".", "Conn", ".", "Opts", ".", "AsyncErrorCB", "(", "c", ".", "Conn", ",", "m", ".", "Sub", ",", "errors", ".", "New", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "argType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "oPtr", "=", "reflect", ".", "Indirect", "(", "oPtr", ")", "\n", "}", "\n\n", "// Callback Arity", "switch", "numArgs", "{", "case", "1", ":", "oV", "=", "[", "]", "reflect", ".", "Value", "{", "oPtr", "}", "\n", "case", "2", ":", "subV", ":=", "reflect", ".", "ValueOf", "(", "m", ".", "Subject", ")", "\n", "oV", "=", "[", "]", "reflect", ".", "Value", "{", "subV", ",", "oPtr", "}", "\n", "case", "3", ":", "subV", ":=", "reflect", ".", "ValueOf", "(", "m", ".", "Subject", ")", "\n", "replyV", ":=", "reflect", ".", "ValueOf", "(", "m", ".", "Reply", ")", "\n", "oV", "=", "[", "]", "reflect", ".", "Value", "{", "subV", ",", "replyV", ",", "oPtr", "}", "\n", "}", "\n\n", "}", "\n", "cbValue", ".", "Call", "(", "oV", ")", "\n", "}", "\n\n", "return", "c", ".", "Conn", ".", "subscribe", "(", "subject", ",", "queue", ",", "natsCB", ",", "nil", ",", "false", ")", "\n", "}" ]
// Internal implementation that all public functions will use.
[ "Internal", "implementation", "that", "all", "public", "functions", "will", "use", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L185-L238
train
nats-io/go-nats
parser.go
cloneMsgArg
func (nc *Conn) cloneMsgArg() { nc.ps.argBuf = nc.ps.scratch[:0] nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.subject...) nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.reply...) nc.ps.ma.subject = nc.ps.argBuf[:len(nc.ps.ma.subject)] if nc.ps.ma.reply != nil { nc.ps.ma.reply = nc.ps.argBuf[len(nc.ps.ma.subject):] } }
go
func (nc *Conn) cloneMsgArg() { nc.ps.argBuf = nc.ps.scratch[:0] nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.subject...) nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.reply...) nc.ps.ma.subject = nc.ps.argBuf[:len(nc.ps.ma.subject)] if nc.ps.ma.reply != nil { nc.ps.ma.reply = nc.ps.argBuf[len(nc.ps.ma.subject):] } }
[ "func", "(", "nc", "*", "Conn", ")", "cloneMsgArg", "(", ")", "{", "nc", ".", "ps", ".", "argBuf", "=", "nc", ".", "ps", ".", "scratch", "[", ":", "0", "]", "\n", "nc", ".", "ps", ".", "argBuf", "=", "append", "(", "nc", ".", "ps", ".", "argBuf", ",", "nc", ".", "ps", ".", "ma", ".", "subject", "...", ")", "\n", "nc", ".", "ps", ".", "argBuf", "=", "append", "(", "nc", ".", "ps", ".", "argBuf", ",", "nc", ".", "ps", ".", "ma", ".", "reply", "...", ")", "\n", "nc", ".", "ps", ".", "ma", ".", "subject", "=", "nc", ".", "ps", ".", "argBuf", "[", ":", "len", "(", "nc", ".", "ps", ".", "ma", ".", "subject", ")", "]", "\n", "if", "nc", ".", "ps", ".", "ma", ".", "reply", "!=", "nil", "{", "nc", ".", "ps", ".", "ma", ".", "reply", "=", "nc", ".", "ps", ".", "argBuf", "[", "len", "(", "nc", ".", "ps", ".", "ma", ".", "subject", ")", ":", "]", "\n", "}", "\n", "}" ]
// cloneMsgArg is used when the split buffer scenario has the pubArg in the existing read buffer, but // we need to hold onto it into the next read.
[ "cloneMsgArg", "is", "used", "when", "the", "split", "buffer", "scenario", "has", "the", "pubArg", "in", "the", "existing", "read", "buffer", "but", "we", "need", "to", "hold", "onto", "it", "into", "the", "next", "read", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/parser.go#L405-L413
train
nats-io/go-nats
nats.go
GetDefaultOptions
func GetDefaultOptions() Options { return Options{ AllowReconnect: true, MaxReconnect: DefaultMaxReconnect, ReconnectWait: DefaultReconnectWait, Timeout: DefaultTimeout, PingInterval: DefaultPingInterval, MaxPingsOut: DefaultMaxPingOut, SubChanLen: DefaultMaxChanLen, ReconnectBufSize: DefaultReconnectBufSize, DrainTimeout: DefaultDrainTimeout, } }
go
func GetDefaultOptions() Options { return Options{ AllowReconnect: true, MaxReconnect: DefaultMaxReconnect, ReconnectWait: DefaultReconnectWait, Timeout: DefaultTimeout, PingInterval: DefaultPingInterval, MaxPingsOut: DefaultMaxPingOut, SubChanLen: DefaultMaxChanLen, ReconnectBufSize: DefaultReconnectBufSize, DrainTimeout: DefaultDrainTimeout, } }
[ "func", "GetDefaultOptions", "(", ")", "Options", "{", "return", "Options", "{", "AllowReconnect", ":", "true", ",", "MaxReconnect", ":", "DefaultMaxReconnect", ",", "ReconnectWait", ":", "DefaultReconnectWait", ",", "Timeout", ":", "DefaultTimeout", ",", "PingInterval", ":", "DefaultPingInterval", ",", "MaxPingsOut", ":", "DefaultMaxPingOut", ",", "SubChanLen", ":", "DefaultMaxChanLen", ",", "ReconnectBufSize", ":", "DefaultReconnectBufSize", ",", "DrainTimeout", ":", "DefaultDrainTimeout", ",", "}", "\n", "}" ]
// GetDefaultOptions returns default configuration options for the client.
[ "GetDefaultOptions", "returns", "default", "configuration", "options", "for", "the", "client", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L117-L129
train
nats-io/go-nats
nats.go
Name
func Name(name string) Option { return func(o *Options) error { o.Name = name return nil } }
go
func Name(name string) Option { return func(o *Options) error { o.Name = name return nil } }
[ "func", "Name", "(", "name", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "Name", "=", "name", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Options that can be passed to Connect. // Name is an Option to set the client name.
[ "Options", "that", "can", "be", "passed", "to", "Connect", ".", "Name", "is", "an", "Option", "to", "set", "the", "client", "name", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L531-L536
train
nats-io/go-nats
nats.go
RootCAs
func RootCAs(file ...string) Option { return func(o *Options) error { pool := x509.NewCertPool() for _, f := range file { rootPEM, err := ioutil.ReadFile(f) if err != nil || rootPEM == nil { return fmt.Errorf("nats: error loading or parsing rootCA file: %v", err) } ok := pool.AppendCertsFromPEM(rootPEM) if !ok { return fmt.Errorf("nats: failed to parse root certificate from %q", f) } } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.RootCAs = pool o.Secure = true return nil } }
go
func RootCAs(file ...string) Option { return func(o *Options) error { pool := x509.NewCertPool() for _, f := range file { rootPEM, err := ioutil.ReadFile(f) if err != nil || rootPEM == nil { return fmt.Errorf("nats: error loading or parsing rootCA file: %v", err) } ok := pool.AppendCertsFromPEM(rootPEM) if !ok { return fmt.Errorf("nats: failed to parse root certificate from %q", f) } } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.RootCAs = pool o.Secure = true return nil } }
[ "func", "RootCAs", "(", "file", "...", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "pool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "for", "_", ",", "f", ":=", "range", "file", "{", "rootPEM", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "f", ")", "\n", "if", "err", "!=", "nil", "||", "rootPEM", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "ok", ":=", "pool", ".", "AppendCertsFromPEM", "(", "rootPEM", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ")", "\n", "}", "\n", "}", "\n", "if", "o", ".", "TLSConfig", "==", "nil", "{", "o", ".", "TLSConfig", "=", "&", "tls", ".", "Config", "{", "MinVersion", ":", "tls", ".", "VersionTLS12", "}", "\n", "}", "\n", "o", ".", "TLSConfig", ".", "RootCAs", "=", "pool", "\n", "o", ".", "Secure", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// RootCAs is a helper option to provide the RootCAs pool from a list of filenames. // If Secure is not already set this will set it as well.
[ "RootCAs", "is", "a", "helper", "option", "to", "provide", "the", "RootCAs", "pool", "from", "a", "list", "of", "filenames", ".", "If", "Secure", "is", "not", "already", "set", "this", "will", "set", "it", "as", "well", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L557-L577
train
nats-io/go-nats
nats.go
ClientCert
func ClientCert(certFile, keyFile string) Option { return func(o *Options) error { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return fmt.Errorf("nats: error loading client certificate: %v", err) } cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) if err != nil { return fmt.Errorf("nats: error parsing client certificate: %v", err) } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.Certificates = []tls.Certificate{cert} o.Secure = true return nil } }
go
func ClientCert(certFile, keyFile string) Option { return func(o *Options) error { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return fmt.Errorf("nats: error loading client certificate: %v", err) } cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) if err != nil { return fmt.Errorf("nats: error parsing client certificate: %v", err) } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.Certificates = []tls.Certificate{cert} o.Secure = true return nil } }
[ "func", "ClientCert", "(", "certFile", ",", "keyFile", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "certFile", ",", "keyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "cert", ".", "Leaf", ",", "err", "=", "x509", ".", "ParseCertificate", "(", "cert", ".", "Certificate", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "o", ".", "TLSConfig", "==", "nil", "{", "o", ".", "TLSConfig", "=", "&", "tls", ".", "Config", "{", "MinVersion", ":", "tls", ".", "VersionTLS12", "}", "\n", "}", "\n", "o", ".", "TLSConfig", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", "\n", "o", ".", "Secure", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ClientCert is a helper option to provide the client certificate from a file. // If Secure is not already set this will set it as well.
[ "ClientCert", "is", "a", "helper", "option", "to", "provide", "the", "client", "certificate", "from", "a", "file", ".", "If", "Secure", "is", "not", "already", "set", "this", "will", "set", "it", "as", "well", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L581-L598
train
nats-io/go-nats
nats.go
ReconnectWait
func ReconnectWait(t time.Duration) Option { return func(o *Options) error { o.ReconnectWait = t return nil } }
go
func ReconnectWait(t time.Duration) Option { return func(o *Options) error { o.ReconnectWait = t return nil } }
[ "func", "ReconnectWait", "(", "t", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ReconnectWait", "=", "t", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ReconnectWait is an Option to set the wait time between reconnect attempts.
[ "ReconnectWait", "is", "an", "Option", "to", "set", "the", "wait", "time", "between", "reconnect", "attempts", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L626-L631
train
nats-io/go-nats
nats.go
MaxReconnects
func MaxReconnects(max int) Option { return func(o *Options) error { o.MaxReconnect = max return nil } }
go
func MaxReconnects(max int) Option { return func(o *Options) error { o.MaxReconnect = max return nil } }
[ "func", "MaxReconnects", "(", "max", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "MaxReconnect", "=", "max", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MaxReconnects is an Option to set the maximum number of reconnect attempts.
[ "MaxReconnects", "is", "an", "Option", "to", "set", "the", "maximum", "number", "of", "reconnect", "attempts", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L634-L639
train
nats-io/go-nats
nats.go
MaxPingsOutstanding
func MaxPingsOutstanding(max int) Option { return func(o *Options) error { o.MaxPingsOut = max return nil } }
go
func MaxPingsOutstanding(max int) Option { return func(o *Options) error { o.MaxPingsOut = max return nil } }
[ "func", "MaxPingsOutstanding", "(", "max", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "MaxPingsOut", "=", "max", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MaxPingsOutstanding is an Option to set the maximum number of ping requests // that can go un-answered by the server before closing the connection.
[ "MaxPingsOutstanding", "is", "an", "Option", "to", "set", "the", "maximum", "number", "of", "ping", "requests", "that", "can", "go", "un", "-", "answered", "by", "the", "server", "before", "closing", "the", "connection", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L651-L656
train
nats-io/go-nats
nats.go
ReconnectBufSize
func ReconnectBufSize(size int) Option { return func(o *Options) error { o.ReconnectBufSize = size return nil } }
go
func ReconnectBufSize(size int) Option { return func(o *Options) error { o.ReconnectBufSize = size return nil } }
[ "func", "ReconnectBufSize", "(", "size", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ReconnectBufSize", "=", "size", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ReconnectBufSize sets the buffer size of messages kept while busy reconnecting.
[ "ReconnectBufSize", "sets", "the", "buffer", "size", "of", "messages", "kept", "while", "busy", "reconnecting", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L659-L664
train
nats-io/go-nats
nats.go
DisconnectHandler
func DisconnectHandler(cb ConnHandler) Option { return func(o *Options) error { o.DisconnectedCB = cb return nil } }
go
func DisconnectHandler(cb ConnHandler) Option { return func(o *Options) error { o.DisconnectedCB = cb return nil } }
[ "func", "DisconnectHandler", "(", "cb", "ConnHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "DisconnectedCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// DisconnectHandler is an Option to set the disconnected handler.
[ "DisconnectHandler", "is", "an", "Option", "to", "set", "the", "disconnected", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L691-L696
train
nats-io/go-nats
nats.go
ReconnectHandler
func ReconnectHandler(cb ConnHandler) Option { return func(o *Options) error { o.ReconnectedCB = cb return nil } }
go
func ReconnectHandler(cb ConnHandler) Option { return func(o *Options) error { o.ReconnectedCB = cb return nil } }
[ "func", "ReconnectHandler", "(", "cb", "ConnHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ReconnectedCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ReconnectHandler is an Option to set the reconnected handler.
[ "ReconnectHandler", "is", "an", "Option", "to", "set", "the", "reconnected", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L699-L704
train
nats-io/go-nats
nats.go
ClosedHandler
func ClosedHandler(cb ConnHandler) Option { return func(o *Options) error { o.ClosedCB = cb return nil } }
go
func ClosedHandler(cb ConnHandler) Option { return func(o *Options) error { o.ClosedCB = cb return nil } }
[ "func", "ClosedHandler", "(", "cb", "ConnHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ClosedCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ClosedHandler is an Option to set the closed handler.
[ "ClosedHandler", "is", "an", "Option", "to", "set", "the", "closed", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L707-L712
train
nats-io/go-nats
nats.go
DiscoveredServersHandler
func DiscoveredServersHandler(cb ConnHandler) Option { return func(o *Options) error { o.DiscoveredServersCB = cb return nil } }
go
func DiscoveredServersHandler(cb ConnHandler) Option { return func(o *Options) error { o.DiscoveredServersCB = cb return nil } }
[ "func", "DiscoveredServersHandler", "(", "cb", "ConnHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "DiscoveredServersCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// DiscoveredServersHandler is an Option to set the new servers handler.
[ "DiscoveredServersHandler", "is", "an", "Option", "to", "set", "the", "new", "servers", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L715-L720
train
nats-io/go-nats
nats.go
ErrorHandler
func ErrorHandler(cb ErrHandler) Option { return func(o *Options) error { o.AsyncErrorCB = cb return nil } }
go
func ErrorHandler(cb ErrHandler) Option { return func(o *Options) error { o.AsyncErrorCB = cb return nil } }
[ "func", "ErrorHandler", "(", "cb", "ErrHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "AsyncErrorCB", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ErrorHandler is an Option to set the async error handler.
[ "ErrorHandler", "is", "an", "Option", "to", "set", "the", "async", "error", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L723-L728
train
nats-io/go-nats
nats.go
UserInfo
func UserInfo(user, password string) Option { return func(o *Options) error { o.User = user o.Password = password return nil } }
go
func UserInfo(user, password string) Option { return func(o *Options) error { o.User = user o.Password = password return nil } }
[ "func", "UserInfo", "(", "user", ",", "password", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "User", "=", "user", "\n", "o", ".", "Password", "=", "password", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// UserInfo is an Option to set the username and password to // use when not included directly in the URLs.
[ "UserInfo", "is", "an", "Option", "to", "set", "the", "username", "and", "password", "to", "use", "when", "not", "included", "directly", "in", "the", "URLs", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L732-L738
train
nats-io/go-nats
nats.go
Token
func Token(token string) Option { return func(o *Options) error { if o.TokenHandler != nil { return ErrTokenAlreadySet } o.Token = token return nil } }
go
func Token(token string) Option { return func(o *Options) error { if o.TokenHandler != nil { return ErrTokenAlreadySet } o.Token = token return nil } }
[ "func", "Token", "(", "token", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "if", "o", ".", "TokenHandler", "!=", "nil", "{", "return", "ErrTokenAlreadySet", "\n", "}", "\n", "o", ".", "Token", "=", "token", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Token is an Option to set the token to use // when a token is not included directly in the URLs // and when a token handler is not provided.
[ "Token", "is", "an", "Option", "to", "set", "the", "token", "to", "use", "when", "a", "token", "is", "not", "included", "directly", "in", "the", "URLs", "and", "when", "a", "token", "handler", "is", "not", "provided", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L743-L751
train
nats-io/go-nats
nats.go
TokenHandler
func TokenHandler(cb AuthTokenHandler) Option { return func(o *Options) error { if o.Token != "" { return ErrTokenAlreadySet } o.TokenHandler = cb return nil } }
go
func TokenHandler(cb AuthTokenHandler) Option { return func(o *Options) error { if o.Token != "" { return ErrTokenAlreadySet } o.TokenHandler = cb return nil } }
[ "func", "TokenHandler", "(", "cb", "AuthTokenHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "if", "o", ".", "Token", "!=", "\"", "\"", "{", "return", "ErrTokenAlreadySet", "\n", "}", "\n", "o", ".", "TokenHandler", "=", "cb", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// TokenHandler is an Option to set the token handler to use // when a token is not included directly in the URLs // and when a token is not set.
[ "TokenHandler", "is", "an", "Option", "to", "set", "the", "token", "handler", "to", "use", "when", "a", "token", "is", "not", "included", "directly", "in", "the", "URLs", "and", "when", "a", "token", "is", "not", "set", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L756-L764
train
nats-io/go-nats
nats.go
UserCredentials
func UserCredentials(userOrChainedFile string, seedFiles ...string) Option { userCB := func() (string, error) { return userFromFile(userOrChainedFile) } var keyFile string if len(seedFiles) > 0 { keyFile = seedFiles[0] } else { keyFile = userOrChainedFile } sigCB := func(nonce []byte) ([]byte, error) { return sigHandler(nonce, keyFile) } return UserJWT(userCB, sigCB) }
go
func UserCredentials(userOrChainedFile string, seedFiles ...string) Option { userCB := func() (string, error) { return userFromFile(userOrChainedFile) } var keyFile string if len(seedFiles) > 0 { keyFile = seedFiles[0] } else { keyFile = userOrChainedFile } sigCB := func(nonce []byte) ([]byte, error) { return sigHandler(nonce, keyFile) } return UserJWT(userCB, sigCB) }
[ "func", "UserCredentials", "(", "userOrChainedFile", "string", ",", "seedFiles", "...", "string", ")", "Option", "{", "userCB", ":=", "func", "(", ")", "(", "string", ",", "error", ")", "{", "return", "userFromFile", "(", "userOrChainedFile", ")", "\n", "}", "\n", "var", "keyFile", "string", "\n", "if", "len", "(", "seedFiles", ")", ">", "0", "{", "keyFile", "=", "seedFiles", "[", "0", "]", "\n", "}", "else", "{", "keyFile", "=", "userOrChainedFile", "\n", "}", "\n", "sigCB", ":=", "func", "(", "nonce", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "sigHandler", "(", "nonce", ",", "keyFile", ")", "\n", "}", "\n", "return", "UserJWT", "(", "userCB", ",", "sigCB", ")", "\n", "}" ]
// UserCredentials is a convenience function that takes a filename // for a user's JWT and a filename for the user's private Nkey seed.
[ "UserCredentials", "is", "a", "convenience", "function", "that", "takes", "a", "filename", "for", "a", "user", "s", "JWT", "and", "a", "filename", "for", "the", "user", "s", "private", "Nkey", "seed", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L768-L782
train
nats-io/go-nats
nats.go
UserJWT
func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option { return func(o *Options) error { if userCB == nil { return ErrNoUserCB } if sigCB == nil { return ErrUserButNoSigCB } o.UserJWT = userCB o.SignatureCB = sigCB return nil } }
go
func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option { return func(o *Options) error { if userCB == nil { return ErrNoUserCB } if sigCB == nil { return ErrUserButNoSigCB } o.UserJWT = userCB o.SignatureCB = sigCB return nil } }
[ "func", "UserJWT", "(", "userCB", "UserJWTHandler", ",", "sigCB", "SignatureHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "if", "userCB", "==", "nil", "{", "return", "ErrNoUserCB", "\n", "}", "\n", "if", "sigCB", "==", "nil", "{", "return", "ErrUserButNoSigCB", "\n", "}", "\n", "o", ".", "UserJWT", "=", "userCB", "\n", "o", ".", "SignatureCB", "=", "sigCB", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// UserJWT will set the callbacks to retrieve the user's JWT and // the signature callback to sign the server nonce. This an the Nkey // option are mutually exclusive.
[ "UserJWT", "will", "set", "the", "callbacks", "to", "retrieve", "the", "user", "s", "JWT", "and", "the", "signature", "callback", "to", "sign", "the", "server", "nonce", ".", "This", "an", "the", "Nkey", "option", "are", "mutually", "exclusive", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L787-L799
train
nats-io/go-nats
nats.go
Nkey
func Nkey(pubKey string, sigCB SignatureHandler) Option { return func(o *Options) error { o.Nkey = pubKey o.SignatureCB = sigCB if pubKey != "" && sigCB == nil { return ErrNkeyButNoSigCB } return nil } }
go
func Nkey(pubKey string, sigCB SignatureHandler) Option { return func(o *Options) error { o.Nkey = pubKey o.SignatureCB = sigCB if pubKey != "" && sigCB == nil { return ErrNkeyButNoSigCB } return nil } }
[ "func", "Nkey", "(", "pubKey", "string", ",", "sigCB", "SignatureHandler", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "Nkey", "=", "pubKey", "\n", "o", ".", "SignatureCB", "=", "sigCB", "\n", "if", "pubKey", "!=", "\"", "\"", "&&", "sigCB", "==", "nil", "{", "return", "ErrNkeyButNoSigCB", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Nkey will set the public Nkey and the signature callback to // sign the server nonce.
[ "Nkey", "will", "set", "the", "public", "Nkey", "and", "the", "signature", "callback", "to", "sign", "the", "server", "nonce", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L803-L812
train
nats-io/go-nats
nats.go
SetCustomDialer
func SetCustomDialer(dialer CustomDialer) Option { return func(o *Options) error { o.CustomDialer = dialer return nil } }
go
func SetCustomDialer(dialer CustomDialer) Option { return func(o *Options) error { o.CustomDialer = dialer return nil } }
[ "func", "SetCustomDialer", "(", "dialer", "CustomDialer", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "CustomDialer", "=", "dialer", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// SetCustomDialer is an Option to set a custom dialer which will be // used when attempting to establish a connection. If both Dialer // and CustomDialer are specified, CustomDialer takes precedence.
[ "SetCustomDialer", "is", "an", "Option", "to", "set", "a", "custom", "dialer", "which", "will", "be", "used", "when", "attempting", "to", "establish", "a", "connection", ".", "If", "both", "Dialer", "and", "CustomDialer", "are", "specified", "CustomDialer", "takes", "precedence", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L836-L841
train
nats-io/go-nats
nats.go
SetDisconnectHandler
func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.DisconnectedCB = dcb }
go
func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.DisconnectedCB = dcb }
[ "func", "(", "nc", "*", "Conn", ")", "SetDisconnectHandler", "(", "dcb", "ConnHandler", ")", "{", "if", "nc", "==", "nil", "{", "return", "\n", "}", "\n", "nc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nc", ".", "mu", ".", "Unlock", "(", ")", "\n", "nc", ".", "Opts", ".", "DisconnectedCB", "=", "dcb", "\n", "}" ]
// Handler processing // SetDisconnectHandler will set the disconnect event handler.
[ "Handler", "processing", "SetDisconnectHandler", "will", "set", "the", "disconnect", "event", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L854-L861
train
nats-io/go-nats
nats.go
SetReconnectHandler
func (nc *Conn) SetReconnectHandler(rcb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.ReconnectedCB = rcb }
go
func (nc *Conn) SetReconnectHandler(rcb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.ReconnectedCB = rcb }
[ "func", "(", "nc", "*", "Conn", ")", "SetReconnectHandler", "(", "rcb", "ConnHandler", ")", "{", "if", "nc", "==", "nil", "{", "return", "\n", "}", "\n", "nc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nc", ".", "mu", ".", "Unlock", "(", ")", "\n", "nc", ".", "Opts", ".", "ReconnectedCB", "=", "rcb", "\n", "}" ]
// SetReconnectHandler will set the reconnect event handler.
[ "SetReconnectHandler", "will", "set", "the", "reconnect", "event", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L864-L871
train
nats-io/go-nats
nats.go
SetDiscoveredServersHandler
func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.DiscoveredServersCB = dscb }
go
func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.DiscoveredServersCB = dscb }
[ "func", "(", "nc", "*", "Conn", ")", "SetDiscoveredServersHandler", "(", "dscb", "ConnHandler", ")", "{", "if", "nc", "==", "nil", "{", "return", "\n", "}", "\n", "nc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nc", ".", "mu", ".", "Unlock", "(", ")", "\n", "nc", ".", "Opts", ".", "DiscoveredServersCB", "=", "dscb", "\n", "}" ]
// SetDiscoveredServersHandler will set the discovered servers handler.
[ "SetDiscoveredServersHandler", "will", "set", "the", "discovered", "servers", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L874-L881
train
nats-io/go-nats
nats.go
SetClosedHandler
func (nc *Conn) SetClosedHandler(cb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.ClosedCB = cb }
go
func (nc *Conn) SetClosedHandler(cb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.ClosedCB = cb }
[ "func", "(", "nc", "*", "Conn", ")", "SetClosedHandler", "(", "cb", "ConnHandler", ")", "{", "if", "nc", "==", "nil", "{", "return", "\n", "}", "\n", "nc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nc", ".", "mu", ".", "Unlock", "(", ")", "\n", "nc", ".", "Opts", ".", "ClosedCB", "=", "cb", "\n", "}" ]
// SetClosedHandler will set the reconnect event handler.
[ "SetClosedHandler", "will", "set", "the", "reconnect", "event", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L884-L891
train
nats-io/go-nats
nats.go
SetErrorHandler
func (nc *Conn) SetErrorHandler(cb ErrHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.AsyncErrorCB = cb }
go
func (nc *Conn) SetErrorHandler(cb ErrHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.AsyncErrorCB = cb }
[ "func", "(", "nc", "*", "Conn", ")", "SetErrorHandler", "(", "cb", "ErrHandler", ")", "{", "if", "nc", "==", "nil", "{", "return", "\n", "}", "\n", "nc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nc", ".", "mu", ".", "Unlock", "(", ")", "\n", "nc", ".", "Opts", ".", "AsyncErrorCB", "=", "cb", "\n", "}" ]
// SetErrorHandler will set the async error handler.
[ "SetErrorHandler", "will", "set", "the", "async", "error", "handler", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L894-L901
train
nats-io/go-nats
nats.go
processUrlString
func processUrlString(url string) []string { urls := strings.Split(url, ",") for i, s := range urls { urls[i] = strings.TrimSpace(s) } return urls }
go
func processUrlString(url string) []string { urls := strings.Split(url, ",") for i, s := range urls { urls[i] = strings.TrimSpace(s) } return urls }
[ "func", "processUrlString", "(", "url", "string", ")", "[", "]", "string", "{", "urls", ":=", "strings", ".", "Split", "(", "url", ",", "\"", "\"", ")", "\n", "for", "i", ",", "s", ":=", "range", "urls", "{", "urls", "[", "i", "]", "=", "strings", ".", "TrimSpace", "(", "s", ")", "\n", "}", "\n", "return", "urls", "\n", "}" ]
// Process the url string argument to Connect. // Return an array of urls, even if only one.
[ "Process", "the", "url", "string", "argument", "to", "Connect", ".", "Return", "an", "array", "of", "urls", "even", "if", "only", "one", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L905-L911
train
nats-io/go-nats
nats.go
Connect
func (o Options) Connect() (*Conn, error) { nc := &Conn{Opts: o} // Some default options processing. if nc.Opts.MaxPingsOut == 0 { nc.Opts.MaxPingsOut = DefaultMaxPingOut } // Allow old default for channel length to work correctly. if nc.Opts.SubChanLen == 0 { nc.Opts.SubChanLen = DefaultMaxChanLen } // Default ReconnectBufSize if nc.Opts.ReconnectBufSize == 0 { nc.Opts.ReconnectBufSize = DefaultReconnectBufSize } // Ensure that Timeout is not 0 if nc.Opts.Timeout == 0 { nc.Opts.Timeout = DefaultTimeout } // Check first for user jwt callback being defined and nkey. if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" { return nil, ErrNkeyAndUser } // Check if we have an nkey but no signature callback defined. if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil { return nil, ErrNkeyButNoSigCB } // Allow custom Dialer for connecting using DialTimeout by default if nc.Opts.Dialer == nil { nc.Opts.Dialer = &net.Dialer{ Timeout: nc.Opts.Timeout, } } if err := nc.setupServerPool(); err != nil { return nil, err } // Create the async callback handler. nc.ach = &asyncCallbacksHandler{} nc.ach.cond = sync.NewCond(&nc.ach.mu) if err := nc.connect(); err != nil { return nil, err } // Spin up the async cb dispatcher on success go nc.ach.asyncCBDispatcher() return nc, nil }
go
func (o Options) Connect() (*Conn, error) { nc := &Conn{Opts: o} // Some default options processing. if nc.Opts.MaxPingsOut == 0 { nc.Opts.MaxPingsOut = DefaultMaxPingOut } // Allow old default for channel length to work correctly. if nc.Opts.SubChanLen == 0 { nc.Opts.SubChanLen = DefaultMaxChanLen } // Default ReconnectBufSize if nc.Opts.ReconnectBufSize == 0 { nc.Opts.ReconnectBufSize = DefaultReconnectBufSize } // Ensure that Timeout is not 0 if nc.Opts.Timeout == 0 { nc.Opts.Timeout = DefaultTimeout } // Check first for user jwt callback being defined and nkey. if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" { return nil, ErrNkeyAndUser } // Check if we have an nkey but no signature callback defined. if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil { return nil, ErrNkeyButNoSigCB } // Allow custom Dialer for connecting using DialTimeout by default if nc.Opts.Dialer == nil { nc.Opts.Dialer = &net.Dialer{ Timeout: nc.Opts.Timeout, } } if err := nc.setupServerPool(); err != nil { return nil, err } // Create the async callback handler. nc.ach = &asyncCallbacksHandler{} nc.ach.cond = sync.NewCond(&nc.ach.mu) if err := nc.connect(); err != nil { return nil, err } // Spin up the async cb dispatcher on success go nc.ach.asyncCBDispatcher() return nc, nil }
[ "func", "(", "o", "Options", ")", "Connect", "(", ")", "(", "*", "Conn", ",", "error", ")", "{", "nc", ":=", "&", "Conn", "{", "Opts", ":", "o", "}", "\n\n", "// Some default options processing.", "if", "nc", ".", "Opts", ".", "MaxPingsOut", "==", "0", "{", "nc", ".", "Opts", ".", "MaxPingsOut", "=", "DefaultMaxPingOut", "\n", "}", "\n", "// Allow old default for channel length to work correctly.", "if", "nc", ".", "Opts", ".", "SubChanLen", "==", "0", "{", "nc", ".", "Opts", ".", "SubChanLen", "=", "DefaultMaxChanLen", "\n", "}", "\n", "// Default ReconnectBufSize", "if", "nc", ".", "Opts", ".", "ReconnectBufSize", "==", "0", "{", "nc", ".", "Opts", ".", "ReconnectBufSize", "=", "DefaultReconnectBufSize", "\n", "}", "\n", "// Ensure that Timeout is not 0", "if", "nc", ".", "Opts", ".", "Timeout", "==", "0", "{", "nc", ".", "Opts", ".", "Timeout", "=", "DefaultTimeout", "\n", "}", "\n\n", "// Check first for user jwt callback being defined and nkey.", "if", "nc", ".", "Opts", ".", "UserJWT", "!=", "nil", "&&", "nc", ".", "Opts", ".", "Nkey", "!=", "\"", "\"", "{", "return", "nil", ",", "ErrNkeyAndUser", "\n", "}", "\n\n", "// Check if we have an nkey but no signature callback defined.", "if", "nc", ".", "Opts", ".", "Nkey", "!=", "\"", "\"", "&&", "nc", ".", "Opts", ".", "SignatureCB", "==", "nil", "{", "return", "nil", ",", "ErrNkeyButNoSigCB", "\n", "}", "\n\n", "// Allow custom Dialer for connecting using DialTimeout by default", "if", "nc", ".", "Opts", ".", "Dialer", "==", "nil", "{", "nc", ".", "Opts", ".", "Dialer", "=", "&", "net", ".", "Dialer", "{", "Timeout", ":", "nc", ".", "Opts", ".", "Timeout", ",", "}", "\n", "}", "\n\n", "if", "err", ":=", "nc", ".", "setupServerPool", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create the async callback handler.", "nc", ".", "ach", "=", "&", "asyncCallbacksHandler", "{", "}", "\n", "nc", ".", "ach", ".", "cond", "=", "sync", ".", "NewCond", "(", "&", "nc", ".", "ach", ".", "mu", ")", "\n\n", "if", "err", ":=", "nc", ".", "connect", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Spin up the async cb dispatcher on success", "go", "nc", ".", "ach", ".", "asyncCBDispatcher", "(", ")", "\n\n", "return", "nc", ",", "nil", "\n", "}" ]
// Connect will attempt to connect to a NATS server with multiple options.
[ "Connect", "will", "attempt", "to", "connect", "to", "a", "NATS", "server", "with", "multiple", "options", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L914-L967
train
nats-io/go-nats
nats.go
currentServer
func (nc *Conn) currentServer() (int, *srv) { for i, s := range nc.srvPool { if s == nil { continue } if s == nc.current { return i, s } } return -1, nil }
go
func (nc *Conn) currentServer() (int, *srv) { for i, s := range nc.srvPool { if s == nil { continue } if s == nc.current { return i, s } } return -1, nil }
[ "func", "(", "nc", "*", "Conn", ")", "currentServer", "(", ")", "(", "int", ",", "*", "srv", ")", "{", "for", "i", ",", "s", ":=", "range", "nc", ".", "srvPool", "{", "if", "s", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "s", "==", "nc", ".", "current", "{", "return", "i", ",", "s", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "nil", "\n", "}" ]
// Return the currently selected server
[ "Return", "the", "currently", "selected", "server" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L993-L1003
train
nats-io/go-nats
nats.go
selectNextServer
func (nc *Conn) selectNextServer() (*srv, error) { i, s := nc.currentServer() if i < 0 { return nil, ErrNoServers } sp := nc.srvPool num := len(sp) copy(sp[i:num-1], sp[i+1:num]) maxReconnect := nc.Opts.MaxReconnect if maxReconnect < 0 || s.reconnects < maxReconnect { nc.srvPool[num-1] = s } else { nc.srvPool = sp[0 : num-1] } if len(nc.srvPool) <= 0 { nc.current = nil return nil, ErrNoServers } nc.current = nc.srvPool[0] return nc.srvPool[0], nil }
go
func (nc *Conn) selectNextServer() (*srv, error) { i, s := nc.currentServer() if i < 0 { return nil, ErrNoServers } sp := nc.srvPool num := len(sp) copy(sp[i:num-1], sp[i+1:num]) maxReconnect := nc.Opts.MaxReconnect if maxReconnect < 0 || s.reconnects < maxReconnect { nc.srvPool[num-1] = s } else { nc.srvPool = sp[0 : num-1] } if len(nc.srvPool) <= 0 { nc.current = nil return nil, ErrNoServers } nc.current = nc.srvPool[0] return nc.srvPool[0], nil }
[ "func", "(", "nc", "*", "Conn", ")", "selectNextServer", "(", ")", "(", "*", "srv", ",", "error", ")", "{", "i", ",", "s", ":=", "nc", ".", "currentServer", "(", ")", "\n", "if", "i", "<", "0", "{", "return", "nil", ",", "ErrNoServers", "\n", "}", "\n", "sp", ":=", "nc", ".", "srvPool", "\n", "num", ":=", "len", "(", "sp", ")", "\n", "copy", "(", "sp", "[", "i", ":", "num", "-", "1", "]", ",", "sp", "[", "i", "+", "1", ":", "num", "]", ")", "\n", "maxReconnect", ":=", "nc", ".", "Opts", ".", "MaxReconnect", "\n", "if", "maxReconnect", "<", "0", "||", "s", ".", "reconnects", "<", "maxReconnect", "{", "nc", ".", "srvPool", "[", "num", "-", "1", "]", "=", "s", "\n", "}", "else", "{", "nc", ".", "srvPool", "=", "sp", "[", "0", ":", "num", "-", "1", "]", "\n", "}", "\n", "if", "len", "(", "nc", ".", "srvPool", ")", "<=", "0", "{", "nc", ".", "current", "=", "nil", "\n", "return", "nil", ",", "ErrNoServers", "\n", "}", "\n", "nc", ".", "current", "=", "nc", ".", "srvPool", "[", "0", "]", "\n", "return", "nc", ".", "srvPool", "[", "0", "]", ",", "nil", "\n", "}" ]
// Pop the current server and put onto the end of the list. Select head of list as long // as number of reconnect attempts under MaxReconnect.
[ "Pop", "the", "current", "server", "and", "put", "onto", "the", "end", "of", "the", "list", ".", "Select", "head", "of", "list", "as", "long", "as", "number", "of", "reconnect", "attempts", "under", "MaxReconnect", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1007-L1027
train
nats-io/go-nats
nats.go
pickServer
func (nc *Conn) pickServer() error { nc.current = nil if len(nc.srvPool) <= 0 { return ErrNoServers } for _, s := range nc.srvPool { if s != nil { nc.current = s return nil } } return ErrNoServers }
go
func (nc *Conn) pickServer() error { nc.current = nil if len(nc.srvPool) <= 0 { return ErrNoServers } for _, s := range nc.srvPool { if s != nil { nc.current = s return nil } } return ErrNoServers }
[ "func", "(", "nc", "*", "Conn", ")", "pickServer", "(", ")", "error", "{", "nc", ".", "current", "=", "nil", "\n", "if", "len", "(", "nc", ".", "srvPool", ")", "<=", "0", "{", "return", "ErrNoServers", "\n", "}", "\n\n", "for", "_", ",", "s", ":=", "range", "nc", ".", "srvPool", "{", "if", "s", "!=", "nil", "{", "nc", ".", "current", "=", "s", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "ErrNoServers", "\n", "}" ]
// Will assign the correct server to nc.current
[ "Will", "assign", "the", "correct", "server", "to", "nc", ".", "current" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1030-L1043
train
nats-io/go-nats
nats.go
setupServerPool
func (nc *Conn) setupServerPool() error { nc.srvPool = make([]*srv, 0, srvPoolSize) nc.urls = make(map[string]struct{}, srvPoolSize) // Create srv objects from each url string in nc.Opts.Servers // and add them to the pool. for _, urlString := range nc.Opts.Servers { if err := nc.addURLToPool(urlString, false, false); err != nil { return err } } // Randomize if allowed to if !nc.Opts.NoRandomize { nc.shufflePool() } // Normally, if this one is set, Options.Servers should not be, // but we always allowed that, so continue to do so. if nc.Opts.Url != _EMPTY_ { // Add to the end of the array if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil { return err } // Then swap it with first to guarantee that Options.Url is tried first. last := len(nc.srvPool) - 1 if last > 0 { nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0] } } else if len(nc.srvPool) <= 0 { // Place default URL if pool is empty. if err := nc.addURLToPool(DefaultURL, false, false); err != nil { return err } } // Check for Scheme hint to move to TLS mode. for _, srv := range nc.srvPool { if srv.url.Scheme == tlsScheme { // FIXME(dlc), this is for all in the pool, should be case by case. nc.Opts.Secure = true if nc.Opts.TLSConfig == nil { nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } } } return nc.pickServer() }
go
func (nc *Conn) setupServerPool() error { nc.srvPool = make([]*srv, 0, srvPoolSize) nc.urls = make(map[string]struct{}, srvPoolSize) // Create srv objects from each url string in nc.Opts.Servers // and add them to the pool. for _, urlString := range nc.Opts.Servers { if err := nc.addURLToPool(urlString, false, false); err != nil { return err } } // Randomize if allowed to if !nc.Opts.NoRandomize { nc.shufflePool() } // Normally, if this one is set, Options.Servers should not be, // but we always allowed that, so continue to do so. if nc.Opts.Url != _EMPTY_ { // Add to the end of the array if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil { return err } // Then swap it with first to guarantee that Options.Url is tried first. last := len(nc.srvPool) - 1 if last > 0 { nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0] } } else if len(nc.srvPool) <= 0 { // Place default URL if pool is empty. if err := nc.addURLToPool(DefaultURL, false, false); err != nil { return err } } // Check for Scheme hint to move to TLS mode. for _, srv := range nc.srvPool { if srv.url.Scheme == tlsScheme { // FIXME(dlc), this is for all in the pool, should be case by case. nc.Opts.Secure = true if nc.Opts.TLSConfig == nil { nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } } } return nc.pickServer() }
[ "func", "(", "nc", "*", "Conn", ")", "setupServerPool", "(", ")", "error", "{", "nc", ".", "srvPool", "=", "make", "(", "[", "]", "*", "srv", ",", "0", ",", "srvPoolSize", ")", "\n", "nc", ".", "urls", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ",", "srvPoolSize", ")", "\n\n", "// Create srv objects from each url string in nc.Opts.Servers", "// and add them to the pool.", "for", "_", ",", "urlString", ":=", "range", "nc", ".", "Opts", ".", "Servers", "{", "if", "err", ":=", "nc", ".", "addURLToPool", "(", "urlString", ",", "false", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Randomize if allowed to", "if", "!", "nc", ".", "Opts", ".", "NoRandomize", "{", "nc", ".", "shufflePool", "(", ")", "\n", "}", "\n\n", "// Normally, if this one is set, Options.Servers should not be,", "// but we always allowed that, so continue to do so.", "if", "nc", ".", "Opts", ".", "Url", "!=", "_EMPTY_", "{", "// Add to the end of the array", "if", "err", ":=", "nc", ".", "addURLToPool", "(", "nc", ".", "Opts", ".", "Url", ",", "false", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Then swap it with first to guarantee that Options.Url is tried first.", "last", ":=", "len", "(", "nc", ".", "srvPool", ")", "-", "1", "\n", "if", "last", ">", "0", "{", "nc", ".", "srvPool", "[", "0", "]", ",", "nc", ".", "srvPool", "[", "last", "]", "=", "nc", ".", "srvPool", "[", "last", "]", ",", "nc", ".", "srvPool", "[", "0", "]", "\n", "}", "\n", "}", "else", "if", "len", "(", "nc", ".", "srvPool", ")", "<=", "0", "{", "// Place default URL if pool is empty.", "if", "err", ":=", "nc", ".", "addURLToPool", "(", "DefaultURL", ",", "false", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Check for Scheme hint to move to TLS mode.", "for", "_", ",", "srv", ":=", "range", "nc", ".", "srvPool", "{", "if", "srv", ".", "url", ".", "Scheme", "==", "tlsScheme", "{", "// FIXME(dlc), this is for all in the pool, should be case by case.", "nc", ".", "Opts", ".", "Secure", "=", "true", "\n", "if", "nc", ".", "Opts", ".", "TLSConfig", "==", "nil", "{", "nc", ".", "Opts", ".", "TLSConfig", "=", "&", "tls", ".", "Config", "{", "MinVersion", ":", "tls", ".", "VersionTLS12", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nc", ".", "pickServer", "(", ")", "\n", "}" ]
// Create the server pool using the options given. // We will place a Url option first, followed by any // Server Options. We will randomize the server pool unless // the NoRandomize flag is set.
[ "Create", "the", "server", "pool", "using", "the", "options", "given", ".", "We", "will", "place", "a", "Url", "option", "first", "followed", "by", "any", "Server", "Options", ".", "We", "will", "randomize", "the", "server", "pool", "unless", "the", "NoRandomize", "flag", "is", "set", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1051-L1099
train
nats-io/go-nats
nats.go
addURLToPool
func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error { if !strings.Contains(sURL, "://") { sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL) } var ( u *url.URL err error ) for i := 0; i < 2; i++ { u, err = url.Parse(sURL) if err != nil { return err } if u.Port() != "" { break } // In case given URL is of the form "localhost:", just add // the port number at the end, otherwise, add ":4222". if sURL[len(sURL)-1] != ':' { sURL += ":" } sURL += defaultPortString } var tlsName string if implicit { curl := nc.current.url // Check to see if we do not have a url.User but current connected // url does. If so copy over. if u.User == nil && curl.User != nil { u.User = curl.User } // We are checking to see if we have a secure connection and are // adding an implicit server that just has an IP. If so we will remember // the current hostname we are connected to. if saveTLSName && hostIsIP(u) { tlsName = curl.Hostname() } } s := &srv{url: u, isImplicit: implicit, tlsName: tlsName} nc.srvPool = append(nc.srvPool, s) nc.urls[u.Host] = struct{}{} return nil }
go
func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error { if !strings.Contains(sURL, "://") { sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL) } var ( u *url.URL err error ) for i := 0; i < 2; i++ { u, err = url.Parse(sURL) if err != nil { return err } if u.Port() != "" { break } // In case given URL is of the form "localhost:", just add // the port number at the end, otherwise, add ":4222". if sURL[len(sURL)-1] != ':' { sURL += ":" } sURL += defaultPortString } var tlsName string if implicit { curl := nc.current.url // Check to see if we do not have a url.User but current connected // url does. If so copy over. if u.User == nil && curl.User != nil { u.User = curl.User } // We are checking to see if we have a secure connection and are // adding an implicit server that just has an IP. If so we will remember // the current hostname we are connected to. if saveTLSName && hostIsIP(u) { tlsName = curl.Hostname() } } s := &srv{url: u, isImplicit: implicit, tlsName: tlsName} nc.srvPool = append(nc.srvPool, s) nc.urls[u.Host] = struct{}{} return nil }
[ "func", "(", "nc", "*", "Conn", ")", "addURLToPool", "(", "sURL", "string", ",", "implicit", ",", "saveTLSName", "bool", ")", "error", "{", "if", "!", "strings", ".", "Contains", "(", "sURL", ",", "\"", "\"", ")", "{", "sURL", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "nc", ".", "connScheme", "(", ")", ",", "sURL", ")", "\n", "}", "\n", "var", "(", "u", "*", "url", ".", "URL", "\n", "err", "error", "\n", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "2", ";", "i", "++", "{", "u", ",", "err", "=", "url", ".", "Parse", "(", "sURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "u", ".", "Port", "(", ")", "!=", "\"", "\"", "{", "break", "\n", "}", "\n", "// In case given URL is of the form \"localhost:\", just add", "// the port number at the end, otherwise, add \":4222\".", "if", "sURL", "[", "len", "(", "sURL", ")", "-", "1", "]", "!=", "':'", "{", "sURL", "+=", "\"", "\"", "\n", "}", "\n", "sURL", "+=", "defaultPortString", "\n", "}", "\n\n", "var", "tlsName", "string", "\n", "if", "implicit", "{", "curl", ":=", "nc", ".", "current", ".", "url", "\n", "// Check to see if we do not have a url.User but current connected", "// url does. If so copy over.", "if", "u", ".", "User", "==", "nil", "&&", "curl", ".", "User", "!=", "nil", "{", "u", ".", "User", "=", "curl", ".", "User", "\n", "}", "\n", "// We are checking to see if we have a secure connection and are", "// adding an implicit server that just has an IP. If so we will remember", "// the current hostname we are connected to.", "if", "saveTLSName", "&&", "hostIsIP", "(", "u", ")", "{", "tlsName", "=", "curl", ".", "Hostname", "(", ")", "\n", "}", "\n", "}", "\n\n", "s", ":=", "&", "srv", "{", "url", ":", "u", ",", "isImplicit", ":", "implicit", ",", "tlsName", ":", "tlsName", "}", "\n", "nc", ".", "srvPool", "=", "append", "(", "nc", ".", "srvPool", ",", "s", ")", "\n", "nc", ".", "urls", "[", "u", ".", "Host", "]", "=", "struct", "{", "}", "{", "}", "\n", "return", "nil", "\n", "}" ]
// addURLToPool adds an entry to the server pool
[ "addURLToPool", "adds", "an", "entry", "to", "the", "server", "pool" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1115-L1159
train
nats-io/go-nats
nats.go
shufflePool
func (nc *Conn) shufflePool() { if len(nc.srvPool) <= 1 { return } source := rand.NewSource(time.Now().UnixNano()) r := rand.New(source) for i := range nc.srvPool { j := r.Intn(i + 1) nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i] } }
go
func (nc *Conn) shufflePool() { if len(nc.srvPool) <= 1 { return } source := rand.NewSource(time.Now().UnixNano()) r := rand.New(source) for i := range nc.srvPool { j := r.Intn(i + 1) nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i] } }
[ "func", "(", "nc", "*", "Conn", ")", "shufflePool", "(", ")", "{", "if", "len", "(", "nc", ".", "srvPool", ")", "<=", "1", "{", "return", "\n", "}", "\n", "source", ":=", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "r", ":=", "rand", ".", "New", "(", "source", ")", "\n", "for", "i", ":=", "range", "nc", ".", "srvPool", "{", "j", ":=", "r", ".", "Intn", "(", "i", "+", "1", ")", "\n", "nc", ".", "srvPool", "[", "i", "]", ",", "nc", ".", "srvPool", "[", "j", "]", "=", "nc", ".", "srvPool", "[", "j", "]", ",", "nc", ".", "srvPool", "[", "i", "]", "\n", "}", "\n", "}" ]
// shufflePool swaps randomly elements in the server pool
[ "shufflePool", "swaps", "randomly", "elements", "in", "the", "server", "pool" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1162-L1172
train
nats-io/go-nats
nats.go
createConn
func (nc *Conn) createConn() (err error) { if nc.Opts.Timeout < 0 { return ErrBadTimeout } if _, cur := nc.currentServer(); cur == nil { return ErrNoServers } else { cur.lastAttempt = time.Now() } // We will auto-expand host names if they resolve to multiple IPs hosts := []string{} u := nc.current.url if net.ParseIP(u.Hostname()) == nil { addrs, _ := net.LookupHost(u.Hostname()) for _, addr := range addrs { hosts = append(hosts, net.JoinHostPort(addr, u.Port())) } } // Fall back to what we were given. if len(hosts) == 0 { hosts = append(hosts, u.Host) } // CustomDialer takes precedence. If not set, use Opts.Dialer which // is set to a default *net.Dialer (in Connect()) if not explicitly // set by the user. dialer := nc.Opts.CustomDialer if dialer == nil { // We will copy and shorten the timeout if we have multiple hosts to try. copyDialer := *nc.Opts.Dialer copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts)) dialer = &copyDialer } if len(hosts) > 1 && !nc.Opts.NoRandomize { rand.Shuffle(len(hosts), func(i, j int) { hosts[i], hosts[j] = hosts[j], hosts[i] }) } for _, host := range hosts { nc.conn, err = dialer.Dial("tcp", host) if err == nil { break } } if err != nil { return err } // No clue why, but this stalls and kills performance on Mac (Mavericks). // https://code.google.com/p/go/issues/detail?id=6930 //if ip, ok := nc.conn.(*net.TCPConn); ok { // ip.SetReadBuffer(defaultBufSize) //} if nc.pending != nil && nc.bw != nil { // Move to pending buffer. nc.bw.Flush() } nc.bw = nc.newBuffer() return nil }
go
func (nc *Conn) createConn() (err error) { if nc.Opts.Timeout < 0 { return ErrBadTimeout } if _, cur := nc.currentServer(); cur == nil { return ErrNoServers } else { cur.lastAttempt = time.Now() } // We will auto-expand host names if they resolve to multiple IPs hosts := []string{} u := nc.current.url if net.ParseIP(u.Hostname()) == nil { addrs, _ := net.LookupHost(u.Hostname()) for _, addr := range addrs { hosts = append(hosts, net.JoinHostPort(addr, u.Port())) } } // Fall back to what we were given. if len(hosts) == 0 { hosts = append(hosts, u.Host) } // CustomDialer takes precedence. If not set, use Opts.Dialer which // is set to a default *net.Dialer (in Connect()) if not explicitly // set by the user. dialer := nc.Opts.CustomDialer if dialer == nil { // We will copy and shorten the timeout if we have multiple hosts to try. copyDialer := *nc.Opts.Dialer copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts)) dialer = &copyDialer } if len(hosts) > 1 && !nc.Opts.NoRandomize { rand.Shuffle(len(hosts), func(i, j int) { hosts[i], hosts[j] = hosts[j], hosts[i] }) } for _, host := range hosts { nc.conn, err = dialer.Dial("tcp", host) if err == nil { break } } if err != nil { return err } // No clue why, but this stalls and kills performance on Mac (Mavericks). // https://code.google.com/p/go/issues/detail?id=6930 //if ip, ok := nc.conn.(*net.TCPConn); ok { // ip.SetReadBuffer(defaultBufSize) //} if nc.pending != nil && nc.bw != nil { // Move to pending buffer. nc.bw.Flush() } nc.bw = nc.newBuffer() return nil }
[ "func", "(", "nc", "*", "Conn", ")", "createConn", "(", ")", "(", "err", "error", ")", "{", "if", "nc", ".", "Opts", ".", "Timeout", "<", "0", "{", "return", "ErrBadTimeout", "\n", "}", "\n", "if", "_", ",", "cur", ":=", "nc", ".", "currentServer", "(", ")", ";", "cur", "==", "nil", "{", "return", "ErrNoServers", "\n", "}", "else", "{", "cur", ".", "lastAttempt", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n\n", "// We will auto-expand host names if they resolve to multiple IPs", "hosts", ":=", "[", "]", "string", "{", "}", "\n", "u", ":=", "nc", ".", "current", ".", "url", "\n\n", "if", "net", ".", "ParseIP", "(", "u", ".", "Hostname", "(", ")", ")", "==", "nil", "{", "addrs", ",", "_", ":=", "net", ".", "LookupHost", "(", "u", ".", "Hostname", "(", ")", ")", "\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "hosts", "=", "append", "(", "hosts", ",", "net", ".", "JoinHostPort", "(", "addr", ",", "u", ".", "Port", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "// Fall back to what we were given.", "if", "len", "(", "hosts", ")", "==", "0", "{", "hosts", "=", "append", "(", "hosts", ",", "u", ".", "Host", ")", "\n", "}", "\n\n", "// CustomDialer takes precedence. If not set, use Opts.Dialer which", "// is set to a default *net.Dialer (in Connect()) if not explicitly", "// set by the user.", "dialer", ":=", "nc", ".", "Opts", ".", "CustomDialer", "\n", "if", "dialer", "==", "nil", "{", "// We will copy and shorten the timeout if we have multiple hosts to try.", "copyDialer", ":=", "*", "nc", ".", "Opts", ".", "Dialer", "\n", "copyDialer", ".", "Timeout", "=", "copyDialer", ".", "Timeout", "/", "time", ".", "Duration", "(", "len", "(", "hosts", ")", ")", "\n", "dialer", "=", "&", "copyDialer", "\n", "}", "\n\n", "if", "len", "(", "hosts", ")", ">", "1", "&&", "!", "nc", ".", "Opts", ".", "NoRandomize", "{", "rand", ".", "Shuffle", "(", "len", "(", "hosts", ")", ",", "func", "(", "i", ",", "j", "int", ")", "{", "hosts", "[", "i", "]", ",", "hosts", "[", "j", "]", "=", "hosts", "[", "j", "]", ",", "hosts", "[", "i", "]", "\n", "}", ")", "\n", "}", "\n", "for", "_", ",", "host", ":=", "range", "hosts", "{", "nc", ".", "conn", ",", "err", "=", "dialer", ".", "Dial", "(", "\"", "\"", ",", "host", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// No clue why, but this stalls and kills performance on Mac (Mavericks).", "// https://code.google.com/p/go/issues/detail?id=6930", "//if ip, ok := nc.conn.(*net.TCPConn); ok {", "//\tip.SetReadBuffer(defaultBufSize)", "//}", "if", "nc", ".", "pending", "!=", "nil", "&&", "nc", ".", "bw", "!=", "nil", "{", "// Move to pending buffer.", "nc", ".", "bw", ".", "Flush", "(", ")", "\n", "}", "\n", "nc", ".", "bw", "=", "nc", ".", "newBuffer", "(", ")", "\n", "return", "nil", "\n", "}" ]
// createConn will connect to the server and wrap the appropriate // bufio structures. It will do the right thing when an existing // connection is in place.
[ "createConn", "will", "connect", "to", "the", "server", "and", "wrap", "the", "appropriate", "bufio", "structures", ".", "It", "will", "do", "the", "right", "thing", "when", "an", "existing", "connection", "is", "in", "place", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1185-L1248
train
nats-io/go-nats
nats.go
makeTLSConn
func (nc *Conn) makeTLSConn() error { // Allow the user to configure their own tls.Config structure. var tlsCopy *tls.Config if nc.Opts.TLSConfig != nil { tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig) } else { tlsCopy = &tls.Config{} } // If its blank we will override it with the current host if tlsCopy.ServerName == _EMPTY_ { if nc.current.tlsName != _EMPTY_ { tlsCopy.ServerName = nc.current.tlsName } else { h, _, _ := net.SplitHostPort(nc.current.url.Host) tlsCopy.ServerName = h } } nc.conn = tls.Client(nc.conn, tlsCopy) conn := nc.conn.(*tls.Conn) if err := conn.Handshake(); err != nil { return err } nc.bw = nc.newBuffer() return nil }
go
func (nc *Conn) makeTLSConn() error { // Allow the user to configure their own tls.Config structure. var tlsCopy *tls.Config if nc.Opts.TLSConfig != nil { tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig) } else { tlsCopy = &tls.Config{} } // If its blank we will override it with the current host if tlsCopy.ServerName == _EMPTY_ { if nc.current.tlsName != _EMPTY_ { tlsCopy.ServerName = nc.current.tlsName } else { h, _, _ := net.SplitHostPort(nc.current.url.Host) tlsCopy.ServerName = h } } nc.conn = tls.Client(nc.conn, tlsCopy) conn := nc.conn.(*tls.Conn) if err := conn.Handshake(); err != nil { return err } nc.bw = nc.newBuffer() return nil }
[ "func", "(", "nc", "*", "Conn", ")", "makeTLSConn", "(", ")", "error", "{", "// Allow the user to configure their own tls.Config structure.", "var", "tlsCopy", "*", "tls", ".", "Config", "\n", "if", "nc", ".", "Opts", ".", "TLSConfig", "!=", "nil", "{", "tlsCopy", "=", "util", ".", "CloneTLSConfig", "(", "nc", ".", "Opts", ".", "TLSConfig", ")", "\n", "}", "else", "{", "tlsCopy", "=", "&", "tls", ".", "Config", "{", "}", "\n", "}", "\n", "// If its blank we will override it with the current host", "if", "tlsCopy", ".", "ServerName", "==", "_EMPTY_", "{", "if", "nc", ".", "current", ".", "tlsName", "!=", "_EMPTY_", "{", "tlsCopy", ".", "ServerName", "=", "nc", ".", "current", ".", "tlsName", "\n", "}", "else", "{", "h", ",", "_", ",", "_", ":=", "net", ".", "SplitHostPort", "(", "nc", ".", "current", ".", "url", ".", "Host", ")", "\n", "tlsCopy", ".", "ServerName", "=", "h", "\n", "}", "\n", "}", "\n", "nc", ".", "conn", "=", "tls", ".", "Client", "(", "nc", ".", "conn", ",", "tlsCopy", ")", "\n", "conn", ":=", "nc", ".", "conn", ".", "(", "*", "tls", ".", "Conn", ")", "\n", "if", "err", ":=", "conn", ".", "Handshake", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "nc", ".", "bw", "=", "nc", ".", "newBuffer", "(", ")", "\n", "return", "nil", "\n", "}" ]
// makeTLSConn will wrap an existing Conn using TLS
[ "makeTLSConn", "will", "wrap", "an", "existing", "Conn", "using", "TLS" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1251-L1275
train
nats-io/go-nats
nats.go
ConnectedUrl
func (nc *Conn) ConnectedUrl() string { if nc == nil { return _EMPTY_ } nc.mu.RLock() defer nc.mu.RUnlock() if nc.status != CONNECTED { return _EMPTY_ } return nc.current.url.String() }
go
func (nc *Conn) ConnectedUrl() string { if nc == nil { return _EMPTY_ } nc.mu.RLock() defer nc.mu.RUnlock() if nc.status != CONNECTED { return _EMPTY_ } return nc.current.url.String() }
[ "func", "(", "nc", "*", "Conn", ")", "ConnectedUrl", "(", ")", "string", "{", "if", "nc", "==", "nil", "{", "return", "_EMPTY_", "\n", "}", "\n\n", "nc", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "nc", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "if", "nc", ".", "status", "!=", "CONNECTED", "{", "return", "_EMPTY_", "\n", "}", "\n", "return", "nc", ".", "current", ".", "url", ".", "String", "(", ")", "\n", "}" ]
// Report the connected server's Url
[ "Report", "the", "connected", "server", "s", "Url" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1291-L1303
train
nats-io/go-nats
nats.go
ConnectedAddr
func (nc *Conn) ConnectedAddr() string { if nc == nil { return _EMPTY_ } nc.mu.RLock() defer nc.mu.RUnlock() if nc.status != CONNECTED { return _EMPTY_ } return nc.conn.RemoteAddr().String() }
go
func (nc *Conn) ConnectedAddr() string { if nc == nil { return _EMPTY_ } nc.mu.RLock() defer nc.mu.RUnlock() if nc.status != CONNECTED { return _EMPTY_ } return nc.conn.RemoteAddr().String() }
[ "func", "(", "nc", "*", "Conn", ")", "ConnectedAddr", "(", ")", "string", "{", "if", "nc", "==", "nil", "{", "return", "_EMPTY_", "\n", "}", "\n\n", "nc", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "nc", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "if", "nc", ".", "status", "!=", "CONNECTED", "{", "return", "_EMPTY_", "\n", "}", "\n", "return", "nc", ".", "conn", ".", "RemoteAddr", "(", ")", ".", "String", "(", ")", "\n", "}" ]
// ConnectedAddr returns the connected server's IP
[ "ConnectedAddr", "returns", "the", "connected", "server", "s", "IP" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1306-L1318
train
nats-io/go-nats
nats.go
ConnectedServerId
func (nc *Conn) ConnectedServerId() string { if nc == nil { return _EMPTY_ } nc.mu.RLock() defer nc.mu.RUnlock() if nc.status != CONNECTED { return _EMPTY_ } return nc.info.Id }
go
func (nc *Conn) ConnectedServerId() string { if nc == nil { return _EMPTY_ } nc.mu.RLock() defer nc.mu.RUnlock() if nc.status != CONNECTED { return _EMPTY_ } return nc.info.Id }
[ "func", "(", "nc", "*", "Conn", ")", "ConnectedServerId", "(", ")", "string", "{", "if", "nc", "==", "nil", "{", "return", "_EMPTY_", "\n", "}", "\n\n", "nc", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "nc", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "if", "nc", ".", "status", "!=", "CONNECTED", "{", "return", "_EMPTY_", "\n", "}", "\n", "return", "nc", ".", "info", ".", "Id", "\n", "}" ]
// Report the connected server's Id
[ "Report", "the", "connected", "server", "s", "Id" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1321-L1333
train
nats-io/go-nats
nats.go
setup
func (nc *Conn) setup() { nc.subs = make(map[int64]*Subscription) nc.pongs = make([]chan struct{}, 0, 8) nc.fch = make(chan struct{}, flushChanSize) // Setup scratch outbound buffer for PUB pub := nc.scratch[:len(_PUB_P_)] copy(pub, _PUB_P_) }
go
func (nc *Conn) setup() { nc.subs = make(map[int64]*Subscription) nc.pongs = make([]chan struct{}, 0, 8) nc.fch = make(chan struct{}, flushChanSize) // Setup scratch outbound buffer for PUB pub := nc.scratch[:len(_PUB_P_)] copy(pub, _PUB_P_) }
[ "func", "(", "nc", "*", "Conn", ")", "setup", "(", ")", "{", "nc", ".", "subs", "=", "make", "(", "map", "[", "int64", "]", "*", "Subscription", ")", "\n", "nc", ".", "pongs", "=", "make", "(", "[", "]", "chan", "struct", "{", "}", ",", "0", ",", "8", ")", "\n\n", "nc", ".", "fch", "=", "make", "(", "chan", "struct", "{", "}", ",", "flushChanSize", ")", "\n\n", "// Setup scratch outbound buffer for PUB", "pub", ":=", "nc", ".", "scratch", "[", ":", "len", "(", "_PUB_P_", ")", "]", "\n", "copy", "(", "pub", ",", "_PUB_P_", ")", "\n", "}" ]
// Low level setup for structs, etc
[ "Low", "level", "setup", "for", "structs", "etc" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1336-L1345
train
nats-io/go-nats
nats.go
processConnectInit
func (nc *Conn) processConnectInit() error { // Set our deadline for the whole connect process nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout)) defer nc.conn.SetDeadline(time.Time{}) // Set our status to connecting. nc.status = CONNECTING // Process the INFO protocol received from the server err := nc.processExpectedInfo() if err != nil { return err } // Send the CONNECT protocol along with the initial PING protocol. // Wait for the PONG response (or any error that we get from the server). err = nc.sendConnect() if err != nil { return err } // Reset the number of PING sent out nc.pout = 0 // Start or reset Timer if nc.Opts.PingInterval > 0 { if nc.ptmr == nil { nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer) } else { nc.ptmr.Reset(nc.Opts.PingInterval) } } // Start the readLoop and flusher go routines, we will wait on both on a reconnect event. nc.wg.Add(2) go nc.readLoop() go nc.flusher() return nil }
go
func (nc *Conn) processConnectInit() error { // Set our deadline for the whole connect process nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout)) defer nc.conn.SetDeadline(time.Time{}) // Set our status to connecting. nc.status = CONNECTING // Process the INFO protocol received from the server err := nc.processExpectedInfo() if err != nil { return err } // Send the CONNECT protocol along with the initial PING protocol. // Wait for the PONG response (or any error that we get from the server). err = nc.sendConnect() if err != nil { return err } // Reset the number of PING sent out nc.pout = 0 // Start or reset Timer if nc.Opts.PingInterval > 0 { if nc.ptmr == nil { nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer) } else { nc.ptmr.Reset(nc.Opts.PingInterval) } } // Start the readLoop and flusher go routines, we will wait on both on a reconnect event. nc.wg.Add(2) go nc.readLoop() go nc.flusher() return nil }
[ "func", "(", "nc", "*", "Conn", ")", "processConnectInit", "(", ")", "error", "{", "// Set our deadline for the whole connect process", "nc", ".", "conn", ".", "SetDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "nc", ".", "Opts", ".", "Timeout", ")", ")", "\n", "defer", "nc", ".", "conn", ".", "SetDeadline", "(", "time", ".", "Time", "{", "}", ")", "\n\n", "// Set our status to connecting.", "nc", ".", "status", "=", "CONNECTING", "\n\n", "// Process the INFO protocol received from the server", "err", ":=", "nc", ".", "processExpectedInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Send the CONNECT protocol along with the initial PING protocol.", "// Wait for the PONG response (or any error that we get from the server).", "err", "=", "nc", ".", "sendConnect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Reset the number of PING sent out", "nc", ".", "pout", "=", "0", "\n\n", "// Start or reset Timer", "if", "nc", ".", "Opts", ".", "PingInterval", ">", "0", "{", "if", "nc", ".", "ptmr", "==", "nil", "{", "nc", ".", "ptmr", "=", "time", ".", "AfterFunc", "(", "nc", ".", "Opts", ".", "PingInterval", ",", "nc", ".", "processPingTimer", ")", "\n", "}", "else", "{", "nc", ".", "ptmr", ".", "Reset", "(", "nc", ".", "Opts", ".", "PingInterval", ")", "\n", "}", "\n", "}", "\n\n", "// Start the readLoop and flusher go routines, we will wait on both on a reconnect event.", "nc", ".", "wg", ".", "Add", "(", "2", ")", "\n", "go", "nc", ".", "readLoop", "(", ")", "\n", "go", "nc", ".", "flusher", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Process a connected connection and initialize properly.
[ "Process", "a", "connected", "connection", "and", "initialize", "properly", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1348-L1388
train
nats-io/go-nats
nats.go
connect
func (nc *Conn) connect() error { var returnedErr error // Create actual socket connection // For first connect we walk all servers in the pool and try // to connect immediately. nc.mu.Lock() nc.initc = true // The pool may change inside the loop iteration due to INFO protocol. for i := 0; i < len(nc.srvPool); i++ { nc.current = nc.srvPool[i] if err := nc.createConn(); err == nil { // This was moved out of processConnectInit() because // that function is now invoked from doReconnect() too. nc.setup() err = nc.processConnectInit() if err == nil { nc.srvPool[i].didConnect = true nc.srvPool[i].reconnects = 0 returnedErr = nil break } else { returnedErr = err nc.mu.Unlock() nc.close(DISCONNECTED, false) nc.mu.Lock() nc.current = nil } } else { // Cancel out default connection refused, will trigger the // No servers error conditional if strings.Contains(err.Error(), "connection refused") { returnedErr = nil } } } nc.initc = false if returnedErr == nil && nc.status != CONNECTED { returnedErr = ErrNoServers } nc.mu.Unlock() return returnedErr }
go
func (nc *Conn) connect() error { var returnedErr error // Create actual socket connection // For first connect we walk all servers in the pool and try // to connect immediately. nc.mu.Lock() nc.initc = true // The pool may change inside the loop iteration due to INFO protocol. for i := 0; i < len(nc.srvPool); i++ { nc.current = nc.srvPool[i] if err := nc.createConn(); err == nil { // This was moved out of processConnectInit() because // that function is now invoked from doReconnect() too. nc.setup() err = nc.processConnectInit() if err == nil { nc.srvPool[i].didConnect = true nc.srvPool[i].reconnects = 0 returnedErr = nil break } else { returnedErr = err nc.mu.Unlock() nc.close(DISCONNECTED, false) nc.mu.Lock() nc.current = nil } } else { // Cancel out default connection refused, will trigger the // No servers error conditional if strings.Contains(err.Error(), "connection refused") { returnedErr = nil } } } nc.initc = false if returnedErr == nil && nc.status != CONNECTED { returnedErr = ErrNoServers } nc.mu.Unlock() return returnedErr }
[ "func", "(", "nc", "*", "Conn", ")", "connect", "(", ")", "error", "{", "var", "returnedErr", "error", "\n\n", "// Create actual socket connection", "// For first connect we walk all servers in the pool and try", "// to connect immediately.", "nc", ".", "mu", ".", "Lock", "(", ")", "\n", "nc", ".", "initc", "=", "true", "\n", "// The pool may change inside the loop iteration due to INFO protocol.", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "nc", ".", "srvPool", ")", ";", "i", "++", "{", "nc", ".", "current", "=", "nc", ".", "srvPool", "[", "i", "]", "\n\n", "if", "err", ":=", "nc", ".", "createConn", "(", ")", ";", "err", "==", "nil", "{", "// This was moved out of processConnectInit() because", "// that function is now invoked from doReconnect() too.", "nc", ".", "setup", "(", ")", "\n\n", "err", "=", "nc", ".", "processConnectInit", "(", ")", "\n\n", "if", "err", "==", "nil", "{", "nc", ".", "srvPool", "[", "i", "]", ".", "didConnect", "=", "true", "\n", "nc", ".", "srvPool", "[", "i", "]", ".", "reconnects", "=", "0", "\n", "returnedErr", "=", "nil", "\n", "break", "\n", "}", "else", "{", "returnedErr", "=", "err", "\n", "nc", ".", "mu", ".", "Unlock", "(", ")", "\n", "nc", ".", "close", "(", "DISCONNECTED", ",", "false", ")", "\n", "nc", ".", "mu", ".", "Lock", "(", ")", "\n", "nc", ".", "current", "=", "nil", "\n", "}", "\n", "}", "else", "{", "// Cancel out default connection refused, will trigger the", "// No servers error conditional", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "returnedErr", "=", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "nc", ".", "initc", "=", "false", "\n", "if", "returnedErr", "==", "nil", "&&", "nc", ".", "status", "!=", "CONNECTED", "{", "returnedErr", "=", "ErrNoServers", "\n", "}", "\n", "nc", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "returnedErr", "\n", "}" ]
// Main connect function. Will connect to the nats-server
[ "Main", "connect", "function", ".", "Will", "connect", "to", "the", "nats", "-", "server" ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1391-L1436
train
nats-io/go-nats
nats.go
checkForSecure
func (nc *Conn) checkForSecure() error { // Check to see if we need to engage TLS o := nc.Opts // Check for mismatch in setups if o.Secure && !nc.info.TLSRequired { return ErrSecureConnWanted } else if nc.info.TLSRequired && !o.Secure { // Switch to Secure since server needs TLS. o.Secure = true } // Need to rewrap with bufio if o.Secure { if err := nc.makeTLSConn(); err != nil { return err } } return nil }
go
func (nc *Conn) checkForSecure() error { // Check to see if we need to engage TLS o := nc.Opts // Check for mismatch in setups if o.Secure && !nc.info.TLSRequired { return ErrSecureConnWanted } else if nc.info.TLSRequired && !o.Secure { // Switch to Secure since server needs TLS. o.Secure = true } // Need to rewrap with bufio if o.Secure { if err := nc.makeTLSConn(); err != nil { return err } } return nil }
[ "func", "(", "nc", "*", "Conn", ")", "checkForSecure", "(", ")", "error", "{", "// Check to see if we need to engage TLS", "o", ":=", "nc", ".", "Opts", "\n\n", "// Check for mismatch in setups", "if", "o", ".", "Secure", "&&", "!", "nc", ".", "info", ".", "TLSRequired", "{", "return", "ErrSecureConnWanted", "\n", "}", "else", "if", "nc", ".", "info", ".", "TLSRequired", "&&", "!", "o", ".", "Secure", "{", "// Switch to Secure since server needs TLS.", "o", ".", "Secure", "=", "true", "\n", "}", "\n\n", "// Need to rewrap with bufio", "if", "o", ".", "Secure", "{", "if", "err", ":=", "nc", ".", "makeTLSConn", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// This will check to see if the connection should be // secure. This can be dictated from either end and should // only be called after the INIT protocol has been received.
[ "This", "will", "check", "to", "see", "if", "the", "connection", "should", "be", "secure", ".", "This", "can", "be", "dictated", "from", "either", "end", "and", "should", "only", "be", "called", "after", "the", "INIT", "protocol", "has", "been", "received", "." ]
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L1441-L1460
train