id
int32
0
167k
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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
14,700
kolide/osquery-go
client.go
Extensions
func (c *ExtensionManagerClient) Extensions() (osquery.InternalExtensionList, error) { return c.Client.Extensions(context.Background()) }
go
func (c *ExtensionManagerClient) Extensions() (osquery.InternalExtensionList, error) { return c.Client.Extensions(context.Background()) }
[ "func", "(", "c", "*", "ExtensionManagerClient", ")", "Extensions", "(", ")", "(", "osquery", ".", "InternalExtensionList", ",", "error", ")", "{", "return", "c", ".", "Client", ".", "Extensions", "(", "context", ".", "Background", "(", ")", ")", "\n", "}" ]
// Extensions requests the list of active registered extensions.
[ "Extensions", "requests", "the", "list", "of", "active", "registered", "extensions", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/client.go#L67-L69
14,701
kolide/osquery-go
client.go
RegisterExtension
func (c *ExtensionManagerClient) RegisterExtension(info *osquery.InternalExtensionInfo, registry osquery.ExtensionRegistry) (*osquery.ExtensionStatus, error) { return c.Client.RegisterExtension(context.Background(), info, registry) }
go
func (c *ExtensionManagerClient) RegisterExtension(info *osquery.InternalExtensionInfo, registry osquery.ExtensionRegistry) (*osquery.ExtensionStatus, error) { return c.Client.RegisterExtension(context.Background(), info, registry) }
[ "func", "(", "c", "*", "ExtensionManagerClient", ")", "RegisterExtension", "(", "info", "*", "osquery", ".", "InternalExtensionInfo", ",", "registry", "osquery", ".", "ExtensionRegistry", ")", "(", "*", "osquery", ".", "ExtensionStatus", ",", "error", ")", "{", "return", "c", ".", "Client", ".", "RegisterExtension", "(", "context", ".", "Background", "(", ")", ",", "info", ",", "registry", ")", "\n", "}" ]
// RegisterExtension registers the extension plugins with the osquery process.
[ "RegisterExtension", "registers", "the", "extension", "plugins", "with", "the", "osquery", "process", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/client.go#L72-L74
14,702
kolide/osquery-go
client.go
Options
func (c *ExtensionManagerClient) Options() (osquery.InternalOptionList, error) { return c.Client.Options(context.Background()) }
go
func (c *ExtensionManagerClient) Options() (osquery.InternalOptionList, error) { return c.Client.Options(context.Background()) }
[ "func", "(", "c", "*", "ExtensionManagerClient", ")", "Options", "(", ")", "(", "osquery", ".", "InternalOptionList", ",", "error", ")", "{", "return", "c", ".", "Client", ".", "Options", "(", "context", ".", "Background", "(", ")", ")", "\n", "}" ]
// Options requests the list of bootstrap or configuration options.
[ "Options", "requests", "the", "list", "of", "bootstrap", "or", "configuration", "options", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/client.go#L77-L79
14,703
kolide/osquery-go
client.go
Query
func (c *ExtensionManagerClient) Query(sql string) (*osquery.ExtensionResponse, error) { return c.Client.Query(context.Background(), sql) }
go
func (c *ExtensionManagerClient) Query(sql string) (*osquery.ExtensionResponse, error) { return c.Client.Query(context.Background(), sql) }
[ "func", "(", "c", "*", "ExtensionManagerClient", ")", "Query", "(", "sql", "string", ")", "(", "*", "osquery", ".", "ExtensionResponse", ",", "error", ")", "{", "return", "c", ".", "Client", ".", "Query", "(", "context", ".", "Background", "(", ")", ",", "sql", ")", "\n", "}" ]
// Query requests a query to be run and returns the extension response. // Consider using the QueryRow or QueryRows helpers for a more friendly // interface.
[ "Query", "requests", "a", "query", "to", "be", "run", "and", "returns", "the", "extension", "response", ".", "Consider", "using", "the", "QueryRow", "or", "QueryRows", "helpers", "for", "a", "more", "friendly", "interface", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/client.go#L84-L86
14,704
kolide/osquery-go
client.go
QueryRows
func (c *ExtensionManagerClient) QueryRows(sql string) ([]map[string]string, error) { res, err := c.Query(sql) if err != nil { return nil, errors.Wrap(err, "transport error in query") } if res.Status == nil { return nil, errors.New("query returned nil status") } if res.Status.Code != 0 { return nil, errors.Errorf("query returned error: %s", res.Status.Message) } return res.Response, nil }
go
func (c *ExtensionManagerClient) QueryRows(sql string) ([]map[string]string, error) { res, err := c.Query(sql) if err != nil { return nil, errors.Wrap(err, "transport error in query") } if res.Status == nil { return nil, errors.New("query returned nil status") } if res.Status.Code != 0 { return nil, errors.Errorf("query returned error: %s", res.Status.Message) } return res.Response, nil }
[ "func", "(", "c", "*", "ExtensionManagerClient", ")", "QueryRows", "(", "sql", "string", ")", "(", "[", "]", "map", "[", "string", "]", "string", ",", "error", ")", "{", "res", ",", "err", ":=", "c", ".", "Query", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "res", ".", "Status", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "res", ".", "Status", ".", "Code", "!=", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "Status", ".", "Message", ")", "\n", "}", "\n", "return", "res", ".", "Response", ",", "nil", "\n\n", "}" ]
// QueryRows is a helper that executes the requested query and returns the // results. It handles checking both the transport level errors and the osquery // internal errors by returning a normal Go error type.
[ "QueryRows", "is", "a", "helper", "that", "executes", "the", "requested", "query", "and", "returns", "the", "results", ".", "It", "handles", "checking", "both", "the", "transport", "level", "errors", "and", "the", "osquery", "internal", "errors", "by", "returning", "a", "normal", "Go", "error", "type", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/client.go#L91-L104
14,705
kolide/osquery-go
client.go
QueryRow
func (c *ExtensionManagerClient) QueryRow(sql string) (map[string]string, error) { res, err := c.QueryRows(sql) if err != nil { return nil, err } if len(res) != 1 { return nil, errors.Errorf("expected 1 row, got %d", len(res)) } return res[0], nil }
go
func (c *ExtensionManagerClient) QueryRow(sql string) (map[string]string, error) { res, err := c.QueryRows(sql) if err != nil { return nil, err } if len(res) != 1 { return nil, errors.Errorf("expected 1 row, got %d", len(res)) } return res[0], nil }
[ "func", "(", "c", "*", "ExtensionManagerClient", ")", "QueryRow", "(", "sql", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "res", ",", "err", ":=", "c", ".", "QueryRows", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "res", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "res", ")", ")", "\n", "}", "\n", "return", "res", "[", "0", "]", ",", "nil", "\n", "}" ]
// QueryRow behaves similarly to QueryRows, but it returns an error if the // query does not return exactly one row.
[ "QueryRow", "behaves", "similarly", "to", "QueryRows", "but", "it", "returns", "an", "error", "if", "the", "query", "does", "not", "return", "exactly", "one", "row", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/client.go#L108-L117
14,706
kolide/osquery-go
plugin/distributed/distributed.go
NewPlugin
func NewPlugin(name string, getQueries GetQueriesFunc, writeResults WriteResultsFunc) *Plugin { return &Plugin{name: name, getQueries: getQueries, writeResults: writeResults} }
go
func NewPlugin(name string, getQueries GetQueriesFunc, writeResults WriteResultsFunc) *Plugin { return &Plugin{name: name, getQueries: getQueries, writeResults: writeResults} }
[ "func", "NewPlugin", "(", "name", "string", ",", "getQueries", "GetQueriesFunc", ",", "writeResults", "WriteResultsFunc", ")", "*", "Plugin", "{", "return", "&", "Plugin", "{", "name", ":", "name", ",", "getQueries", ":", "getQueries", ",", "writeResults", ":", "writeResults", "}", "\n", "}" ]
// NewPlugin takes the distributed query functions and returns a struct // implementing the OsqueryPlugin interface. Use this to wrap the appropriate // functions into an osquery plugin.
[ "NewPlugin", "takes", "the", "distributed", "query", "functions", "and", "returns", "a", "struct", "implementing", "the", "OsqueryPlugin", "interface", ".", "Use", "this", "to", "wrap", "the", "appropriate", "functions", "into", "an", "osquery", "plugin", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/plugin/distributed/distributed.go#L66-L68
14,707
kolide/osquery-go
plugin/distributed/distributed.go
UnmarshalJSON
func (oi *OsqueryInt) UnmarshalJSON(buff []byte) error { s := string(buff) if strings.Contains(s, `"`) { unquoted, err := strconv.Unquote(s) if err != nil { return &json.UnmarshalTypeError{ Value: string(buff), Type: reflect.TypeOf(oi), Struct: "statuses", } } s = unquoted } if len(s) == 0 { *oi = OsqueryInt(0) return nil } parsedInt, err := strconv.ParseInt(s, 10, 32) if err != nil { return &json.UnmarshalTypeError{ Value: string(buff), Type: reflect.TypeOf(oi), Struct: "statuses", } } *oi = OsqueryInt(parsedInt) return nil }
go
func (oi *OsqueryInt) UnmarshalJSON(buff []byte) error { s := string(buff) if strings.Contains(s, `"`) { unquoted, err := strconv.Unquote(s) if err != nil { return &json.UnmarshalTypeError{ Value: string(buff), Type: reflect.TypeOf(oi), Struct: "statuses", } } s = unquoted } if len(s) == 0 { *oi = OsqueryInt(0) return nil } parsedInt, err := strconv.ParseInt(s, 10, 32) if err != nil { return &json.UnmarshalTypeError{ Value: string(buff), Type: reflect.TypeOf(oi), Struct: "statuses", } } *oi = OsqueryInt(parsedInt) return nil }
[ "func", "(", "oi", "*", "OsqueryInt", ")", "UnmarshalJSON", "(", "buff", "[", "]", "byte", ")", "error", "{", "s", ":=", "string", "(", "buff", ")", "\n", "if", "strings", ".", "Contains", "(", "s", ",", "`\"`", ")", "{", "unquoted", ",", "err", ":=", "strconv", ".", "Unquote", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "json", ".", "UnmarshalTypeError", "{", "Value", ":", "string", "(", "buff", ")", ",", "Type", ":", "reflect", ".", "TypeOf", "(", "oi", ")", ",", "Struct", ":", "\"", "\"", ",", "}", "\n", "}", "\n", "s", "=", "unquoted", "\n", "}", "\n\n", "if", "len", "(", "s", ")", "==", "0", "{", "*", "oi", "=", "OsqueryInt", "(", "0", ")", "\n", "return", "nil", "\n", "}", "\n\n", "parsedInt", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "json", ".", "UnmarshalTypeError", "{", "Value", ":", "string", "(", "buff", ")", ",", "Type", ":", "reflect", ".", "TypeOf", "(", "oi", ")", ",", "Struct", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "*", "oi", "=", "OsqueryInt", "(", "parsedInt", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON marshals a json string that is convertable to an int, for // example "234" -> 234.
[ "UnmarshalJSON", "marshals", "a", "json", "string", "that", "is", "convertable", "to", "an", "int", "for", "example", "234", "-", ">", "234", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/plugin/distributed/distributed.go#L106-L136
14,708
kolide/osquery-go
plugin/distributed/distributed.go
UnmarshalJSON
func (rs *ResultsStruct) UnmarshalJSON(buff []byte) error { emptyRow := []map[string]string{} rs.Queries = make(map[string][]map[string]string) rs.Statuses = make(map[string]OsqueryInt) // Queries can be []map[string]string OR an empty string // so we need to deal with an interface to accomodate two types intermediate := struct { Queries map[string]interface{} `json:"queries"` Statuses map[string]OsqueryInt `json:"statuses"` }{} if err := json.Unmarshal(buff, &intermediate); err != nil { return err } for queryName, status := range intermediate.Statuses { rs.Statuses[queryName] = status // Sometimes we have a status but don't have a corresponding // result. queryResult, ok := intermediate.Queries[queryName] if !ok { rs.Queries[queryName] = emptyRow continue } // Deal with structurally inconsistent results, sometimes a query // without any results is just a name with an empty string. switch val := queryResult.(type) { case string: rs.Queries[queryName] = emptyRow case []interface{}: results, err := convertRows(val) if err != nil { return err } rs.Queries[queryName] = results default: return fmt.Errorf("results for %q unknown type", queryName) } } return nil }
go
func (rs *ResultsStruct) UnmarshalJSON(buff []byte) error { emptyRow := []map[string]string{} rs.Queries = make(map[string][]map[string]string) rs.Statuses = make(map[string]OsqueryInt) // Queries can be []map[string]string OR an empty string // so we need to deal with an interface to accomodate two types intermediate := struct { Queries map[string]interface{} `json:"queries"` Statuses map[string]OsqueryInt `json:"statuses"` }{} if err := json.Unmarshal(buff, &intermediate); err != nil { return err } for queryName, status := range intermediate.Statuses { rs.Statuses[queryName] = status // Sometimes we have a status but don't have a corresponding // result. queryResult, ok := intermediate.Queries[queryName] if !ok { rs.Queries[queryName] = emptyRow continue } // Deal with structurally inconsistent results, sometimes a query // without any results is just a name with an empty string. switch val := queryResult.(type) { case string: rs.Queries[queryName] = emptyRow case []interface{}: results, err := convertRows(val) if err != nil { return err } rs.Queries[queryName] = results default: return fmt.Errorf("results for %q unknown type", queryName) } } return nil }
[ "func", "(", "rs", "*", "ResultsStruct", ")", "UnmarshalJSON", "(", "buff", "[", "]", "byte", ")", "error", "{", "emptyRow", ":=", "[", "]", "map", "[", "string", "]", "string", "{", "}", "\n", "rs", ".", "Queries", "=", "make", "(", "map", "[", "string", "]", "[", "]", "map", "[", "string", "]", "string", ")", "\n", "rs", ".", "Statuses", "=", "make", "(", "map", "[", "string", "]", "OsqueryInt", ")", "\n", "// Queries can be []map[string]string OR an empty string", "// so we need to deal with an interface to accomodate two types", "intermediate", ":=", "struct", "{", "Queries", "map", "[", "string", "]", "interface", "{", "}", "`json:\"queries\"`", "\n", "Statuses", "map", "[", "string", "]", "OsqueryInt", "`json:\"statuses\"`", "\n", "}", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "buff", ",", "&", "intermediate", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "queryName", ",", "status", ":=", "range", "intermediate", ".", "Statuses", "{", "rs", ".", "Statuses", "[", "queryName", "]", "=", "status", "\n", "// Sometimes we have a status but don't have a corresponding", "// result.", "queryResult", ",", "ok", ":=", "intermediate", ".", "Queries", "[", "queryName", "]", "\n", "if", "!", "ok", "{", "rs", ".", "Queries", "[", "queryName", "]", "=", "emptyRow", "\n", "continue", "\n", "}", "\n", "// Deal with structurally inconsistent results, sometimes a query", "// without any results is just a name with an empty string.", "switch", "val", ":=", "queryResult", ".", "(", "type", ")", "{", "case", "string", ":", "rs", ".", "Queries", "[", "queryName", "]", "=", "emptyRow", "\n", "case", "[", "]", "interface", "{", "}", ":", "results", ",", "err", ":=", "convertRows", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "rs", ".", "Queries", "[", "queryName", "]", "=", "results", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "queryName", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON turns structurally inconsistent osquery json into a ResultsStruct.
[ "UnmarshalJSON", "turns", "structurally", "inconsistent", "osquery", "json", "into", "a", "ResultsStruct", "." ]
be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0
https://github.com/kolide/osquery-go/blob/be0a8de4cf1d32b0e06dc867f0af55d00cfdfda0/plugin/distributed/distributed.go#L145-L183
14,709
arschles/go-in-5-minutes
episode13/models/person.go
CreatePersonTable
func CreatePersonTable(db *sql.DB) (sql.Result, error) { return db.Exec( fmt.Sprintf("CREATE TABLE %s (%s varchar(255), %s varchar(255), %s int)", PersonTableName, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, ), ) }
go
func CreatePersonTable(db *sql.DB) (sql.Result, error) { return db.Exec( fmt.Sprintf("CREATE TABLE %s (%s varchar(255), %s varchar(255), %s int)", PersonTableName, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, ), ) }
[ "func", "CreatePersonTable", "(", "db", "*", "sql", ".", "DB", ")", "(", "sql", ".", "Result", ",", "error", ")", "{", "return", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "PersonTableName", ",", "PersonFirstNameCol", ",", "PersonLastNameCol", ",", "PersonAgeCol", ",", ")", ",", ")", "\n", "}" ]
// CreatePersonTable uses db to create a new table for Person models, and returns the result
[ "CreatePersonTable", "uses", "db", "to", "create", "a", "new", "table", "for", "Person", "models", "and", "returns", "the", "result" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode13/models/person.go#L27-L36
14,710
arschles/go-in-5-minutes
episode13/models/person.go
InsertPerson
func InsertPerson(db *sql.DB, person Person) (sql.Result, error) { return db.Exec( fmt.Sprintf("INSERT INTO %s VALUES(?, ?, ?)", PersonTableName), person.FirstName, person.LastName, person.Age, ) }
go
func InsertPerson(db *sql.DB, person Person) (sql.Result, error) { return db.Exec( fmt.Sprintf("INSERT INTO %s VALUES(?, ?, ?)", PersonTableName), person.FirstName, person.LastName, person.Age, ) }
[ "func", "InsertPerson", "(", "db", "*", "sql", ".", "DB", ",", "person", "Person", ")", "(", "sql", ".", "Result", ",", "error", ")", "{", "return", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "PersonTableName", ")", ",", "person", ".", "FirstName", ",", "person", ".", "LastName", ",", "person", ".", "Age", ",", ")", "\n", "}" ]
// InsertPerson inserts person into db
[ "InsertPerson", "inserts", "person", "into", "db" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode13/models/person.go#L39-L46
14,711
arschles/go-in-5-minutes
episode13/models/person.go
SelectPerson
func SelectPerson(db *sql.DB, firstName, lastName string, age uint, result *Person) error { row := db.QueryRow( fmt.Sprintf( "SELECT * FROM %s WHERE %s=? AND %s=? AND %s=?", PersonTableName, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, ), firstName, lastName, age, ) var retFirstName, retLastName string var retAge uint if err := row.Scan(&retFirstName, &retLastName, &retAge); err != nil { return err } result.FirstName = retFirstName result.LastName = retLastName result.Age = retAge return nil }
go
func SelectPerson(db *sql.DB, firstName, lastName string, age uint, result *Person) error { row := db.QueryRow( fmt.Sprintf( "SELECT * FROM %s WHERE %s=? AND %s=? AND %s=?", PersonTableName, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, ), firstName, lastName, age, ) var retFirstName, retLastName string var retAge uint if err := row.Scan(&retFirstName, &retLastName, &retAge); err != nil { return err } result.FirstName = retFirstName result.LastName = retLastName result.Age = retAge return nil }
[ "func", "SelectPerson", "(", "db", "*", "sql", ".", "DB", ",", "firstName", ",", "lastName", "string", ",", "age", "uint", ",", "result", "*", "Person", ")", "error", "{", "row", ":=", "db", ".", "QueryRow", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "PersonTableName", ",", "PersonFirstNameCol", ",", "PersonLastNameCol", ",", "PersonAgeCol", ",", ")", ",", "firstName", ",", "lastName", ",", "age", ",", ")", "\n", "var", "retFirstName", ",", "retLastName", "string", "\n", "var", "retAge", "uint", "\n", "if", "err", ":=", "row", ".", "Scan", "(", "&", "retFirstName", ",", "&", "retLastName", ",", "&", "retAge", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "result", ".", "FirstName", "=", "retFirstName", "\n", "result", ".", "LastName", "=", "retLastName", "\n", "result", ".", "Age", "=", "retAge", "\n", "return", "nil", "\n", "}" ]
// SelectPerson selects a person with the given first & last names and age. On success, writes the result into result and on failure, returns a non-nil error and makes no modifications to result
[ "SelectPerson", "selects", "a", "person", "with", "the", "given", "first", "&", "last", "names", "and", "age", ".", "On", "success", "writes", "the", "result", "into", "result", "and", "on", "failure", "returns", "a", "non", "-", "nil", "error", "and", "makes", "no", "modifications", "to", "result" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode13/models/person.go#L49-L71
14,712
arschles/go-in-5-minutes
episode13/models/person.go
UpdatePerson
func UpdatePerson(db *sql.DB, firstName, lastName string, age uint, newPerson Person) error { _, err := db.Exec( fmt.Sprintf( "UPDATE %s SET %s=?,%s=?,%s=? WHERE %s=? AND %s=? AND %s=?", PersonTableName, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, ), newPerson.FirstName, newPerson.LastName, newPerson.Age, firstName, lastName, age, ) return err }
go
func UpdatePerson(db *sql.DB, firstName, lastName string, age uint, newPerson Person) error { _, err := db.Exec( fmt.Sprintf( "UPDATE %s SET %s=?,%s=?,%s=? WHERE %s=? AND %s=? AND %s=?", PersonTableName, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, ), newPerson.FirstName, newPerson.LastName, newPerson.Age, firstName, lastName, age, ) return err }
[ "func", "UpdatePerson", "(", "db", "*", "sql", ".", "DB", ",", "firstName", ",", "lastName", "string", ",", "age", "uint", ",", "newPerson", "Person", ")", "error", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "PersonTableName", ",", "PersonFirstNameCol", ",", "PersonLastNameCol", ",", "PersonAgeCol", ",", "PersonFirstNameCol", ",", "PersonLastNameCol", ",", "PersonAgeCol", ",", ")", ",", "newPerson", ".", "FirstName", ",", "newPerson", ".", "LastName", ",", "newPerson", ".", "Age", ",", "firstName", ",", "lastName", ",", "age", ",", ")", "\n", "return", "err", "\n", "}" ]
// UpdatePerson updates the person with the given first & last names and age with newPerson. Returns a non-nil error if the update failed, and nil if the update succeeded
[ "UpdatePerson", "updates", "the", "person", "with", "the", "given", "first", "&", "last", "names", "and", "age", "with", "newPerson", ".", "Returns", "a", "non", "-", "nil", "error", "if", "the", "update", "failed", "and", "nil", "if", "the", "update", "succeeded" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode13/models/person.go#L74-L94
14,713
arschles/go-in-5-minutes
episode13/models/person.go
DeletePerson
func DeletePerson(db *sql.DB, firstName, lastName string, age uint) error { _, err := db.Exec( fmt.Sprintf( "DELETE FROM %s WHERE %s=? AND %s=? AND %s=?", PersonTableName, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, ), firstName, lastName, age, ) return err }
go
func DeletePerson(db *sql.DB, firstName, lastName string, age uint) error { _, err := db.Exec( fmt.Sprintf( "DELETE FROM %s WHERE %s=? AND %s=? AND %s=?", PersonTableName, PersonFirstNameCol, PersonLastNameCol, PersonAgeCol, ), firstName, lastName, age, ) return err }
[ "func", "DeletePerson", "(", "db", "*", "sql", ".", "DB", ",", "firstName", ",", "lastName", "string", ",", "age", "uint", ")", "error", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "PersonTableName", ",", "PersonFirstNameCol", ",", "PersonLastNameCol", ",", "PersonAgeCol", ",", ")", ",", "firstName", ",", "lastName", ",", "age", ",", ")", "\n", "return", "err", "\n", "}" ]
// DeletePerson deletes the person with the given first & last names and age. Returns a non-nil error if the delete failed, and nil if the delete succeeded
[ "DeletePerson", "deletes", "the", "person", "with", "the", "given", "first", "&", "last", "names", "and", "age", ".", "Returns", "a", "non", "-", "nil", "error", "if", "the", "delete", "failed", "and", "nil", "if", "the", "delete", "succeeded" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode13/models/person.go#L97-L111
14,714
arschles/go-in-5-minutes
episode22/actions/otheraction.go
OtherHandler
func OtherHandler(c buffalo.Context) error { name := c.Param("name") c.Set("name", name) return c.Render(200, r.HTML("other.html")) }
go
func OtherHandler(c buffalo.Context) error { name := c.Param("name") c.Set("name", name) return c.Render(200, r.HTML("other.html")) }
[ "func", "OtherHandler", "(", "c", "buffalo", ".", "Context", ")", "error", "{", "name", ":=", "c", ".", "Param", "(", "\"", "\"", ")", "\n", "c", ".", "Set", "(", "\"", "\"", ",", "name", ")", "\n", "return", "c", ".", "Render", "(", "200", ",", "r", ".", "HTML", "(", "\"", "\"", ")", ")", "\n", "}" ]
// OtherHandler is a default handler to serve up // a home page.
[ "OtherHandler", "is", "a", "default", "handler", "to", "serve", "up", "a", "home", "page", "." ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode22/actions/otheraction.go#L7-L11
14,715
arschles/go-in-5-minutes
episode5/handlers/renderer.go
NewRenderRenderer
func NewRenderRenderer(dir string, extensions []string, funcs []template.FuncMap, dev bool) *RenderRenderer { opts := render.Options{ Directory: dir, Extensions: extensions, Funcs: funcs, IsDevelopment: dev, } return &RenderRenderer{r: render.New(opts)} }
go
func NewRenderRenderer(dir string, extensions []string, funcs []template.FuncMap, dev bool) *RenderRenderer { opts := render.Options{ Directory: dir, Extensions: extensions, Funcs: funcs, IsDevelopment: dev, } return &RenderRenderer{r: render.New(opts)} }
[ "func", "NewRenderRenderer", "(", "dir", "string", ",", "extensions", "[", "]", "string", ",", "funcs", "[", "]", "template", ".", "FuncMap", ",", "dev", "bool", ")", "*", "RenderRenderer", "{", "opts", ":=", "render", ".", "Options", "{", "Directory", ":", "dir", ",", "Extensions", ":", "extensions", ",", "Funcs", ":", "funcs", ",", "IsDevelopment", ":", "dev", ",", "}", "\n", "return", "&", "RenderRenderer", "{", "r", ":", "render", ".", "New", "(", "opts", ")", "}", "\n", "}" ]
// NewRenderRenderer returns a new RenderRenderer, where the underlying render.Render // serves templates out of dir with the given func map. it's configured in dev mode // according to the dev boolean
[ "NewRenderRenderer", "returns", "a", "new", "RenderRenderer", "where", "the", "underlying", "render", ".", "Render", "serves", "templates", "out", "of", "dir", "with", "the", "given", "func", "map", ".", "it", "s", "configured", "in", "dev", "mode", "according", "to", "the", "dev", "boolean" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode5/handlers/renderer.go#L29-L37
14,716
arschles/go-in-5-minutes
episode5/handlers/renderer.go
Render
func (r *RenderRenderer) Render(w http.ResponseWriter, code int, templateName string, data interface{}, layout string) { if layout != "" { r.r.HTML(w, code, templateName, data, render.HTMLOptions{Layout: layout}) return } r.r.HTML(w, code, templateName, data) }
go
func (r *RenderRenderer) Render(w http.ResponseWriter, code int, templateName string, data interface{}, layout string) { if layout != "" { r.r.HTML(w, code, templateName, data, render.HTMLOptions{Layout: layout}) return } r.r.HTML(w, code, templateName, data) }
[ "func", "(", "r", "*", "RenderRenderer", ")", "Render", "(", "w", "http", ".", "ResponseWriter", ",", "code", "int", ",", "templateName", "string", ",", "data", "interface", "{", "}", ",", "layout", "string", ")", "{", "if", "layout", "!=", "\"", "\"", "{", "r", ".", "r", ".", "HTML", "(", "w", ",", "code", ",", "templateName", ",", "data", ",", "render", ".", "HTMLOptions", "{", "Layout", ":", "layout", "}", ")", "\n", "return", "\n", "}", "\n", "r", ".", "r", ".", "HTML", "(", "w", ",", "code", ",", "templateName", ",", "data", ")", "\n", "}" ]
// Render is the interface implementation
[ "Render", "is", "the", "interface", "implementation" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode5/handlers/renderer.go#L40-L46
14,717
arschles/go-in-5-minutes
episode9/conf/conf.go
NewMem
func NewMem() Data { return &memData{l: &sync.RWMutex{}, strings: make(map[string]string), ints: make(map[string]int)} }
go
func NewMem() Data { return &memData{l: &sync.RWMutex{}, strings: make(map[string]string), ints: make(map[string]int)} }
[ "func", "NewMem", "(", ")", "Data", "{", "return", "&", "memData", "{", "l", ":", "&", "sync", ".", "RWMutex", "{", "}", ",", "strings", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "ints", ":", "make", "(", "map", "[", "string", "]", "int", ")", "}", "\n", "}" ]
// NewMem creates a Data implementation that stores config data in memory
[ "NewMem", "creates", "a", "Data", "implementation", "that", "stores", "config", "data", "in", "memory" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode9/conf/conf.go#L40-L42
14,718
arschles/go-in-5-minutes
episode9/conf/conf.go
SetInt
func (m *memData) SetInt(name string, i int) { m.l.Lock() defer m.l.Unlock() m.ints[name] = i }
go
func (m *memData) SetInt(name string, i int) { m.l.Lock() defer m.l.Unlock() m.ints[name] = i }
[ "func", "(", "m", "*", "memData", ")", "SetInt", "(", "name", "string", ",", "i", "int", ")", "{", "m", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "l", ".", "Unlock", "(", ")", "\n", "m", ".", "ints", "[", "name", "]", "=", "i", "\n", "}" ]
// SetInt is the interface implementation
[ "SetInt", "is", "the", "interface", "implementation" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode9/conf/conf.go#L45-L49
14,719
arschles/go-in-5-minutes
episode9/conf/conf.go
GetInt
func (m *memData) GetInt(name string) (int, error) { m.l.RLock() defer m.l.RUnlock() i, ok := m.ints[name] if !ok { return 0, ErrNotFound } return i, nil }
go
func (m *memData) GetInt(name string) (int, error) { m.l.RLock() defer m.l.RUnlock() i, ok := m.ints[name] if !ok { return 0, ErrNotFound } return i, nil }
[ "func", "(", "m", "*", "memData", ")", "GetInt", "(", "name", "string", ")", "(", "int", ",", "error", ")", "{", "m", ".", "l", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "l", ".", "RUnlock", "(", ")", "\n", "i", ",", "ok", ":=", "m", ".", "ints", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "0", ",", "ErrNotFound", "\n", "}", "\n", "return", "i", ",", "nil", "\n", "}" ]
// GetInt is the interface implementation
[ "GetInt", "is", "the", "interface", "implementation" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode9/conf/conf.go#L52-L60
14,720
arschles/go-in-5-minutes
episode11/db/mem.go
Save
func (m *Mem) Save(key models.Key, model models.Model) error { m.mut.Lock() defer m.mut.Unlock() m.m[key.String()] = model return nil }
go
func (m *Mem) Save(key models.Key, model models.Model) error { m.mut.Lock() defer m.mut.Unlock() m.m[key.String()] = model return nil }
[ "func", "(", "m", "*", "Mem", ")", "Save", "(", "key", "models", ".", "Key", ",", "model", "models", ".", "Model", ")", "error", "{", "m", ".", "mut", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mut", ".", "Unlock", "(", ")", "\n", "m", ".", "m", "[", "key", ".", "String", "(", ")", "]", "=", "model", "\n", "return", "nil", "\n", "}" ]
// Save is the interface implementation. Overwrites existing keys and never returns an error
[ "Save", "is", "the", "interface", "implementation", ".", "Overwrites", "existing", "keys", "and", "never", "returns", "an", "error" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode11/db/mem.go#L25-L30
14,721
arschles/go-in-5-minutes
episode11/db/mem.go
Delete
func (m *Mem) Delete(key models.Key) error { m.mut.Lock() defer m.mut.Unlock() delete(m.m, key.String()) return nil }
go
func (m *Mem) Delete(key models.Key) error { m.mut.Lock() defer m.mut.Unlock() delete(m.m, key.String()) return nil }
[ "func", "(", "m", "*", "Mem", ")", "Delete", "(", "key", "models", ".", "Key", ")", "error", "{", "m", ".", "mut", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mut", ".", "Unlock", "(", ")", "\n", "delete", "(", "m", ".", "m", ",", "key", ".", "String", "(", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Delete is the interface implementation. Never returns an error, even if the key didn't exist
[ "Delete", "is", "the", "interface", "implementation", ".", "Never", "returns", "an", "error", "even", "if", "the", "key", "didn", "t", "exist" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode11/db/mem.go#L33-L38
14,722
arschles/go-in-5-minutes
episode11/db/mem.go
Get
func (m *Mem) Get(key models.Key, model models.Model) error { m.mut.RLock() defer m.mut.RUnlock() md, ok := m.m[key.String()] if !ok { return ErrNotFound } return model.Set(md) }
go
func (m *Mem) Get(key models.Key, model models.Model) error { m.mut.RLock() defer m.mut.RUnlock() md, ok := m.m[key.String()] if !ok { return ErrNotFound } return model.Set(md) }
[ "func", "(", "m", "*", "Mem", ")", "Get", "(", "key", "models", ".", "Key", ",", "model", "models", ".", "Model", ")", "error", "{", "m", ".", "mut", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mut", ".", "RUnlock", "(", ")", "\n", "md", ",", "ok", ":=", "m", ".", "m", "[", "key", ".", "String", "(", ")", "]", "\n", "if", "!", "ok", "{", "return", "ErrNotFound", "\n", "}", "\n", "return", "model", ".", "Set", "(", "md", ")", "\n", "}" ]
// Get is the interface implementation. Returns ErrNotFound if no such key existed. Callers should pass a pointer to a model so that Get can write the fetched model into it
[ "Get", "is", "the", "interface", "implementation", ".", "Returns", "ErrNotFound", "if", "no", "such", "key", "existed", ".", "Callers", "should", "pass", "a", "pointer", "to", "a", "model", "so", "that", "Get", "can", "write", "the", "fetched", "model", "into", "it" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode11/db/mem.go#L41-L49
14,723
arschles/go-in-5-minutes
episode12/dishes/manager.go
randDishIdx
func (m *Manager) randDishIdx() int { if len(m.dishes) == 0 { return -1 } return rand.Intn(len(m.dishes)) }
go
func (m *Manager) randDishIdx() int { if len(m.dishes) == 0 { return -1 } return rand.Intn(len(m.dishes)) }
[ "func", "(", "m", "*", "Manager", ")", "randDishIdx", "(", ")", "int", "{", "if", "len", "(", "m", ".", "dishes", ")", "==", "0", "{", "return", "-", "1", "\n", "}", "\n", "return", "rand", ".", "Intn", "(", "len", "(", "m", ".", "dishes", ")", ")", "\n", "}" ]
// randDishIdx returns a random index into the dishes slice, or -1 if the slice // is empty
[ "randDishIdx", "returns", "a", "random", "index", "into", "the", "dishes", "slice", "or", "-", "1", "if", "the", "slice", "is", "empty" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode12/dishes/manager.go#L68-L73
14,724
arschles/go-in-5-minutes
episode24/actions/app.go
App
func App() *buffalo.App { if app == nil { app = buffalo.New(buffalo.Options{ Env: ENV, SessionName: "_episode24_session", }) // Automatically redirect to SSL app.Use(ssl.ForceSSL(secure.Options{ SSLRedirect: ENV == "production", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, })) if ENV == "development" { app.Use(middleware.ParameterLogger) } // Protect against CSRF attacks. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) // Remove to disable this. app.Use(csrf.New) // Wraps each request in a transaction. // c.Value("tx").(*pop.PopTransaction) // Remove to disable this. app.Use(middleware.PopTransaction(models.DB)) // Setup and use translations: var err error if T, err = i18n.New(packr.NewBox("../locales"), "en-US"); err != nil { app.Stop(err) } app.Use(T.Middleware()) app.GET("/", HomeHandler) app.Resource("/gifms", GifmsResource{}) app.ServeFiles("/", assetsBox) // serve files from the public directory } return app }
go
func App() *buffalo.App { if app == nil { app = buffalo.New(buffalo.Options{ Env: ENV, SessionName: "_episode24_session", }) // Automatically redirect to SSL app.Use(ssl.ForceSSL(secure.Options{ SSLRedirect: ENV == "production", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, })) if ENV == "development" { app.Use(middleware.ParameterLogger) } // Protect against CSRF attacks. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) // Remove to disable this. app.Use(csrf.New) // Wraps each request in a transaction. // c.Value("tx").(*pop.PopTransaction) // Remove to disable this. app.Use(middleware.PopTransaction(models.DB)) // Setup and use translations: var err error if T, err = i18n.New(packr.NewBox("../locales"), "en-US"); err != nil { app.Stop(err) } app.Use(T.Middleware()) app.GET("/", HomeHandler) app.Resource("/gifms", GifmsResource{}) app.ServeFiles("/", assetsBox) // serve files from the public directory } return app }
[ "func", "App", "(", ")", "*", "buffalo", ".", "App", "{", "if", "app", "==", "nil", "{", "app", "=", "buffalo", ".", "New", "(", "buffalo", ".", "Options", "{", "Env", ":", "ENV", ",", "SessionName", ":", "\"", "\"", ",", "}", ")", "\n", "// Automatically redirect to SSL", "app", ".", "Use", "(", "ssl", ".", "ForceSSL", "(", "secure", ".", "Options", "{", "SSLRedirect", ":", "ENV", "==", "\"", "\"", ",", "SSLProxyHeaders", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", "}", ",", "}", ")", ")", "\n\n", "if", "ENV", "==", "\"", "\"", "{", "app", ".", "Use", "(", "middleware", ".", "ParameterLogger", ")", "\n", "}", "\n\n", "// Protect against CSRF attacks. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)", "// Remove to disable this.", "app", ".", "Use", "(", "csrf", ".", "New", ")", "\n\n", "// Wraps each request in a transaction.", "// c.Value(\"tx\").(*pop.PopTransaction)", "// Remove to disable this.", "app", ".", "Use", "(", "middleware", ".", "PopTransaction", "(", "models", ".", "DB", ")", ")", "\n\n", "// Setup and use translations:", "var", "err", "error", "\n", "if", "T", ",", "err", "=", "i18n", ".", "New", "(", "packr", ".", "NewBox", "(", "\"", "\"", ")", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "app", ".", "Stop", "(", "err", ")", "\n", "}", "\n", "app", ".", "Use", "(", "T", ".", "Middleware", "(", ")", ")", "\n\n", "app", ".", "GET", "(", "\"", "\"", ",", "HomeHandler", ")", "\n\n", "app", ".", "Resource", "(", "\"", "\"", ",", "GifmsResource", "{", "}", ")", "\n", "app", ".", "ServeFiles", "(", "\"", "\"", ",", "assetsBox", ")", "// serve files from the public directory", "\n", "}", "\n\n", "return", "app", "\n", "}" ]
// App is where all routes and middleware for buffalo // should be defined. This is the nerve center of your // application.
[ "App", "is", "where", "all", "routes", "and", "middleware", "for", "buffalo", "should", "be", "defined", ".", "This", "is", "the", "nerve", "center", "of", "your", "application", "." ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode24/actions/app.go#L25-L64
14,725
arschles/go-in-5-minutes
episode3/admin_api_handlers.go
releaseAllServers
func releaseAllServers(w http.ResponseWriter, r *http.Request) { mx.Lock() defer mx.Unlock() for _, status := range servers { status.Reserved = false } if err := json.NewEncoder(w).Encode(servers); err != nil { log.Printf("[JSON Encoding Error] %s", err) http.Error(w, err.Error(), http.StatusNoContent) } }
go
func releaseAllServers(w http.ResponseWriter, r *http.Request) { mx.Lock() defer mx.Unlock() for _, status := range servers { status.Reserved = false } if err := json.NewEncoder(w).Encode(servers); err != nil { log.Printf("[JSON Encoding Error] %s", err) http.Error(w, err.Error(), http.StatusNoContent) } }
[ "func", "releaseAllServers", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "mx", ".", "Lock", "(", ")", "\n", "defer", "mx", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "status", ":=", "range", "servers", "{", "status", ".", "Reserved", "=", "false", "\n", "}", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "w", ")", ".", "Encode", "(", "servers", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusNoContent", ")", "\n", "}", "\n", "}" ]
// releaseAllServers is the handler to release the lock on all servers. it's an admin-only handler
[ "releaseAllServers", "is", "the", "handler", "to", "release", "the", "lock", "on", "all", "servers", ".", "it", "s", "an", "admin", "-", "only", "handler" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode3/admin_api_handlers.go#L10-L20
14,726
arschles/go-in-5-minutes
episode3/admin_api_handlers.go
getAllServers
func getAllServers(w http.ResponseWriter, r *http.Request) { mx.RLock() defer mx.RUnlock() if err := json.NewEncoder(w).Encode(servers); err != nil { log.Printf("[JSON Encoding Error] %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) } }
go
func getAllServers(w http.ResponseWriter, r *http.Request) { mx.RLock() defer mx.RUnlock() if err := json.NewEncoder(w).Encode(servers); err != nil { log.Printf("[JSON Encoding Error] %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) } }
[ "func", "getAllServers", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "mx", ".", "RLock", "(", ")", "\n", "defer", "mx", ".", "RUnlock", "(", ")", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "w", ")", ".", "Encode", "(", "servers", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "}" ]
// getAllServers is the handler to get the status of all servers. it's admin-only
[ "getAllServers", "is", "the", "handler", "to", "get", "the", "status", "of", "all", "servers", ".", "it", "s", "admin", "-", "only" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode3/admin_api_handlers.go#L23-L30
14,727
arschles/go-in-5-minutes
episode11/db/redis.go
Save
func (r *Redis) Save(k models.Key, m models.Model) error { b, err := m.MarshalBinary() if err != nil { return err } return r.client.Set(k.String(), b, time.Duration(0)).Err() }
go
func (r *Redis) Save(k models.Key, m models.Model) error { b, err := m.MarshalBinary() if err != nil { return err } return r.client.Set(k.String(), b, time.Duration(0)).Err() }
[ "func", "(", "r", "*", "Redis", ")", "Save", "(", "k", "models", ".", "Key", ",", "m", "models", ".", "Model", ")", "error", "{", "b", ",", "err", ":=", "m", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "r", ".", "client", ".", "Set", "(", "k", ".", "String", "(", ")", ",", "b", ",", "time", ".", "Duration", "(", "0", ")", ")", ".", "Err", "(", ")", "\n", "}" ]
// Save is the interface implementation
[ "Save", "is", "the", "interface", "implementation" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode11/db/redis.go#L21-L27
14,728
arschles/go-in-5-minutes
episode11/db/redis.go
Delete
func (r *Redis) Delete(k models.Key) error { return r.client.Del(k.String()).Err() }
go
func (r *Redis) Delete(k models.Key) error { return r.client.Del(k.String()).Err() }
[ "func", "(", "r", "*", "Redis", ")", "Delete", "(", "k", "models", ".", "Key", ")", "error", "{", "return", "r", ".", "client", ".", "Del", "(", "k", ".", "String", "(", ")", ")", ".", "Err", "(", ")", "\n", "}" ]
// Delete is the interface implementation
[ "Delete", "is", "the", "interface", "implementation" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode11/db/redis.go#L30-L32
14,729
arschles/go-in-5-minutes
episode14/main.go
hdl
func hdl(t *template.Template) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Notice that t.Execute takes an io.Writer as its first argument. The variable w (an http.ResponseWriter) implements io.Writer, so we pass it and allow the implementation to call its Write function as necessary if err := t.Execute(w, r.URL.Query()); err != nil { http.Error(w, fmt.Sprintf("error executing template (%s)", err), http.StatusInternalServerError) } }) }
go
func hdl(t *template.Template) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Notice that t.Execute takes an io.Writer as its first argument. The variable w (an http.ResponseWriter) implements io.Writer, so we pass it and allow the implementation to call its Write function as necessary if err := t.Execute(w, r.URL.Query()); err != nil { http.Error(w, fmt.Sprintf("error executing template (%s)", err), http.StatusInternalServerError) } }) }
[ "func", "hdl", "(", "t", "*", "template", ".", "Template", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Notice that t.Execute takes an io.Writer as its first argument. The variable w (an http.ResponseWriter) implements io.Writer, so we pass it and allow the implementation to call its Write function as necessary", "if", "err", ":=", "t", ".", "Execute", "(", "w", ",", "r", ".", "URL", ".", "Query", "(", ")", ")", ";", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// hdl is a handler that calls t.Execute, passing all of the query string values as data to the template
[ "hdl", "is", "a", "handler", "that", "calls", "t", ".", "Execute", "passing", "all", "of", "the", "query", "string", "values", "as", "data", "to", "the", "template" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode14/main.go#L11-L18
14,730
arschles/go-in-5-minutes
episode11/conf.go
GetConfig
func GetConfig() (*Config, error) { conf := new(Config) if err := envconfig.Process(AppName, conf); err != nil { return nil, err } return conf, nil }
go
func GetConfig() (*Config, error) { conf := new(Config) if err := envconfig.Process(AppName, conf); err != nil { return nil, err } return conf, nil }
[ "func", "GetConfig", "(", ")", "(", "*", "Config", ",", "error", ")", "{", "conf", ":=", "new", "(", "Config", ")", "\n", "if", "err", ":=", "envconfig", ".", "Process", "(", "AppName", ",", "conf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "conf", ",", "nil", "\n", "}" ]
// GetConfig uses envconfig to populate and return a Config struct. Returns all envconfig errors if they occurred
[ "GetConfig", "uses", "envconfig", "to", "populate", "and", "return", "a", "Config", "struct", ".", "Returns", "all", "envconfig", "errors", "if", "they", "occurred" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode11/conf.go#L21-L27
14,731
arschles/go-in-5-minutes
episode16/set.go
exists
func (s *set) exists(elt setElement) bool { _, ok := s.m[elt] return ok }
go
func (s *set) exists(elt setElement) bool { _, ok := s.m[elt] return ok }
[ "func", "(", "s", "*", "set", ")", "exists", "(", "elt", "setElement", ")", "bool", "{", "_", ",", "ok", ":=", "s", ".", "m", "[", "elt", "]", "\n", "return", "ok", "\n", "}" ]
// returns true if elt already exists in s
[ "returns", "true", "if", "elt", "already", "exists", "in", "s" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode16/set.go#L18-L21
14,732
arschles/go-in-5-minutes
episode16/set.go
add
func (s *set) add(elt setElement) bool { _, ok := s.m[elt] s.m[elt] = struct{}{} return !ok }
go
func (s *set) add(elt setElement) bool { _, ok := s.m[elt] s.m[elt] = struct{}{} return !ok }
[ "func", "(", "s", "*", "set", ")", "add", "(", "elt", "setElement", ")", "bool", "{", "_", ",", "ok", ":=", "s", ".", "m", "[", "elt", "]", "\n", "s", ".", "m", "[", "elt", "]", "=", "struct", "{", "}", "{", "}", "\n", "return", "!", "ok", "\n", "}" ]
// adds elt to s unless it already exists. returns true if it was added successfully
[ "adds", "elt", "to", "s", "unless", "it", "already", "exists", ".", "returns", "true", "if", "it", "was", "added", "successfully" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode16/set.go#L24-L28
14,733
arschles/go-in-5-minutes
episode16/set.go
remove
func (s *set) remove(elt setElement) bool { _, ok := s.m[elt] if !ok { return false } delete(s.m, elt) return true }
go
func (s *set) remove(elt setElement) bool { _, ok := s.m[elt] if !ok { return false } delete(s.m, elt) return true }
[ "func", "(", "s", "*", "set", ")", "remove", "(", "elt", "setElement", ")", "bool", "{", "_", ",", "ok", ":=", "s", ".", "m", "[", "elt", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "delete", "(", "s", ".", "m", ",", "elt", ")", "\n", "return", "true", "\n", "}" ]
// removes elt from s unless it doesn't exist. returns true if it was removed, false otherwise
[ "removes", "elt", "from", "s", "unless", "it", "doesn", "t", "exist", ".", "returns", "true", "if", "it", "was", "removed", "false", "otherwise" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode16/set.go#L31-L38
14,734
arschles/go-in-5-minutes
episode16/set.go
removeAll
func (s *set) removeAll() int { ret := len(s.m) s.m = make(map[setElement]struct{}) return ret }
go
func (s *set) removeAll() int { ret := len(s.m) s.m = make(map[setElement]struct{}) return ret }
[ "func", "(", "s", "*", "set", ")", "removeAll", "(", ")", "int", "{", "ret", ":=", "len", "(", "s", ".", "m", ")", "\n", "s", ".", "m", "=", "make", "(", "map", "[", "setElement", "]", "struct", "{", "}", ")", "\n", "return", "ret", "\n", "}" ]
// removeAll removes all elements from s and returns the total number of elements removed
[ "removeAll", "removes", "all", "elements", "from", "s", "and", "returns", "the", "total", "number", "of", "elements", "removed" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode16/set.go#L41-L45
14,735
arschles/go-in-5-minutes
episode11/models/app.go
UnmarshalBinary
func (a *App) UnmarshalBinary(b []byte) error { return json.Unmarshal(b, a) }
go
func (a *App) UnmarshalBinary(b []byte) error { return json.Unmarshal(b, a) }
[ "func", "(", "a", "*", "App", ")", "UnmarshalBinary", "(", "b", "[", "]", "byte", ")", "error", "{", "return", "json", ".", "Unmarshal", "(", "b", ",", "a", ")", "\n", "}" ]
// UnmarshalBinary is the encoding.BinaryUnmarshaler interface implementation
[ "UnmarshalBinary", "is", "the", "encoding", ".", "BinaryUnmarshaler", "interface", "implementation" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode11/models/app.go#L37-L39
14,736
arschles/go-in-5-minutes
episode11/models/app.go
Set
func (a *App) Set(m Model) error { app, ok := m.(*App) if !ok { return fmt.Errorf("given model %+v was not an *App", m) } *a = *app return nil }
go
func (a *App) Set(m Model) error { app, ok := m.(*App) if !ok { return fmt.Errorf("given model %+v was not an *App", m) } *a = *app return nil }
[ "func", "(", "a", "*", "App", ")", "Set", "(", "m", "Model", ")", "error", "{", "app", ",", "ok", ":=", "m", ".", "(", "*", "App", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ")", "\n", "}", "\n", "*", "a", "=", "*", "app", "\n", "return", "nil", "\n", "}" ]
// Set is the Model interface implementation
[ "Set", "is", "the", "Model", "interface", "implementation" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode11/models/app.go#L42-L49
14,737
arschles/go-in-5-minutes
episode1/handlers/get_key.go
GetKey
func GetKey(db storage.DB) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { key := r.URL.Query().Get("key") if key == "" { http.Error(w, "missing key name in query string", http.StatusBadRequest) return } val, err := db.Get(key) if err == storage.ErrNotFound { http.Error(w, "not found", http.StatusNotFound) return } else if err != nil { http.Error(w, fmt.Sprintf("error getting value from database: %s", err), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.Write(val) }) }
go
func GetKey(db storage.DB) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { key := r.URL.Query().Get("key") if key == "" { http.Error(w, "missing key name in query string", http.StatusBadRequest) return } val, err := db.Get(key) if err == storage.ErrNotFound { http.Error(w, "not found", http.StatusNotFound) return } else if err != nil { http.Error(w, fmt.Sprintf("error getting value from database: %s", err), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.Write(val) }) }
[ "func", "GetKey", "(", "db", "storage", ".", "DB", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "key", ":=", "r", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "key", "==", "\"", "\"", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "val", ",", "err", ":=", "db", ".", "Get", "(", "key", ")", "\n", "if", "err", "==", "storage", ".", "ErrNotFound", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusNotFound", ")", "\n", "return", "\n", "}", "else", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "w", ".", "Write", "(", "val", ")", "\n", "}", ")", "\n", "}" ]
// GetKey returns an http.Handler that can get a key registered by Gorilla mux // as "key" in the path. It gets the value of the key from db
[ "GetKey", "returns", "an", "http", ".", "Handler", "that", "can", "get", "a", "key", "registered", "by", "Gorilla", "mux", "as", "key", "in", "the", "path", ".", "It", "gets", "the", "value", "of", "the", "key", "from", "db" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode1/handlers/get_key.go#L12-L30
14,738
arschles/go-in-5-minutes
episode5/models/mongo_db.go
Upsert
func (m *MongoDB) Upsert(key string, val Model) (bool, error) { sess := m.sess.Copy() defer sess.Close() coll := sess.DB(dbName).C(candiesColl) cInfo, err := coll.Upsert(bson.M{"key": key}, objWrapper{Key: key, Data: val}) if err != nil { return false, err } // the Updated field is set when already existed, otherwise the UpsertedID field is set. // see the func at https://bazaar.launchpad.net/+branch/mgo/v2/view/head:/session.go#L1896 return cInfo.UpsertedId != nil, nil }
go
func (m *MongoDB) Upsert(key string, val Model) (bool, error) { sess := m.sess.Copy() defer sess.Close() coll := sess.DB(dbName).C(candiesColl) cInfo, err := coll.Upsert(bson.M{"key": key}, objWrapper{Key: key, Data: val}) if err != nil { return false, err } // the Updated field is set when already existed, otherwise the UpsertedID field is set. // see the func at https://bazaar.launchpad.net/+branch/mgo/v2/view/head:/session.go#L1896 return cInfo.UpsertedId != nil, nil }
[ "func", "(", "m", "*", "MongoDB", ")", "Upsert", "(", "key", "string", ",", "val", "Model", ")", "(", "bool", ",", "error", ")", "{", "sess", ":=", "m", ".", "sess", ".", "Copy", "(", ")", "\n", "defer", "sess", ".", "Close", "(", ")", "\n", "coll", ":=", "sess", ".", "DB", "(", "dbName", ")", ".", "C", "(", "candiesColl", ")", "\n", "cInfo", ",", "err", ":=", "coll", ".", "Upsert", "(", "bson", ".", "M", "{", "\"", "\"", ":", "key", "}", ",", "objWrapper", "{", "Key", ":", "key", ",", "Data", ":", "val", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "// the Updated field is set when already existed, otherwise the UpsertedID field is set.", "// see the func at https://bazaar.launchpad.net/+branch/mgo/v2/view/head:/session.go#L1896", "return", "cInfo", ".", "UpsertedId", "!=", "nil", ",", "nil", "\n", "}" ]
// Upsert is the interface implementation
[ "Upsert", "is", "the", "interface", "implementation" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode5/models/mongo_db.go#L74-L85
14,739
arschles/go-in-5-minutes
episode3/api_handlers.go
releaseServer
func releaseServer(w http.ResponseWriter, r *http.Request) { name, ok := mux.Vars(r)["name"] if !ok { http.Error(w, "name missing in URL path", http.StatusBadRequest) return } mx.Lock() defer mx.Unlock() server, ok := servers[name] if !ok { http.Error(w, "no such server", http.StatusNotFound) return } server.Reserved = false if err := json.NewEncoder(w).Encode(server); err != nil { log.Printf("[JSON Encoding Error] %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) } }
go
func releaseServer(w http.ResponseWriter, r *http.Request) { name, ok := mux.Vars(r)["name"] if !ok { http.Error(w, "name missing in URL path", http.StatusBadRequest) return } mx.Lock() defer mx.Unlock() server, ok := servers[name] if !ok { http.Error(w, "no such server", http.StatusNotFound) return } server.Reserved = false if err := json.NewEncoder(w).Encode(server); err != nil { log.Printf("[JSON Encoding Error] %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) } }
[ "func", "releaseServer", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "name", ",", "ok", ":=", "mux", ".", "Vars", "(", "r", ")", "[", "\"", "\"", "]", "\n", "if", "!", "ok", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "mx", ".", "Lock", "(", ")", "\n", "defer", "mx", ".", "Unlock", "(", ")", "\n", "server", ",", "ok", ":=", "servers", "[", "name", "]", "\n", "if", "!", "ok", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusNotFound", ")", "\n", "return", "\n", "}", "\n", "server", ".", "Reserved", "=", "false", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "w", ")", ".", "Encode", "(", "server", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "}" ]
// releaseServer is the handler to release a specific server by name
[ "releaseServer", "is", "the", "handler", "to", "release", "a", "specific", "server", "by", "name" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode3/api_handlers.go#L58-L76
14,740
arschles/go-in-5-minutes
episode1/handlers/put_key.go
PutKey
func PutKey(db storage.DB) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { key := r.URL.Query().Get("key") if key == "" { http.Error(w, "missing key name in path", http.StatusBadRequest) return } defer r.Body.Close() val, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "error reading PUT body", http.StatusBadRequest) return } if err := db.Set(key, val); err != nil { http.Error(w, "error setting value in DB", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }) }
go
func PutKey(db storage.DB) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { key := r.URL.Query().Get("key") if key == "" { http.Error(w, "missing key name in path", http.StatusBadRequest) return } defer r.Body.Close() val, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "error reading PUT body", http.StatusBadRequest) return } if err := db.Set(key, val); err != nil { http.Error(w, "error setting value in DB", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }) }
[ "func", "PutKey", "(", "db", "storage", ".", "DB", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "key", ":=", "r", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "key", "==", "\"", "\"", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "defer", "r", ".", "Body", ".", "Close", "(", ")", "\n", "val", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "db", ".", "Set", "(", "key", ",", "val", ")", ";", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "}", ")", "\n", "}" ]
// PutKey returns an http.Handler that can set a value for the key registered by Gorilla // mux as "key" in the path. It expects the value to be in the body of the PUT request
[ "PutKey", "returns", "an", "http", ".", "Handler", "that", "can", "set", "a", "value", "for", "the", "key", "registered", "by", "Gorilla", "mux", "as", "key", "in", "the", "path", ".", "It", "expects", "the", "value", "to", "be", "in", "the", "body", "of", "the", "PUT", "request" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode1/handlers/put_key.go#L12-L31
14,741
arschles/go-in-5-minutes
episode0/redis_database.go
Get
func (i RedisClientWrapper) Get(key string) ([]byte, error) { val, ok := i.Client.Get(key).Result() if ok != nil { return nil, fmt.Errorf("Error: %s", ok) } return []byte(val), nil }
go
func (i RedisClientWrapper) Get(key string) ([]byte, error) { val, ok := i.Client.Get(key).Result() if ok != nil { return nil, fmt.Errorf("Error: %s", ok) } return []byte(val), nil }
[ "func", "(", "i", "RedisClientWrapper", ")", "Get", "(", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "val", ",", "ok", ":=", "i", ".", "Client", ".", "Get", "(", "key", ")", ".", "Result", "(", ")", "\n", "if", "ok", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ok", ")", "\n", "}", "\n", "return", "[", "]", "byte", "(", "val", ")", ",", "nil", "\n", "}" ]
//Get method of the RedisClientWrapper type
[ "Get", "method", "of", "the", "RedisClientWrapper", "type" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode0/redis_database.go#L16-L22
14,742
arschles/go-in-5-minutes
episode0/redis_database.go
Set
func (i RedisClientWrapper) Set(key string, val []byte) error { err := i.Client.Set(key, val, 0).Err() return err }
go
func (i RedisClientWrapper) Set(key string, val []byte) error { err := i.Client.Set(key, val, 0).Err() return err }
[ "func", "(", "i", "RedisClientWrapper", ")", "Set", "(", "key", "string", ",", "val", "[", "]", "byte", ")", "error", "{", "err", ":=", "i", ".", "Client", ".", "Set", "(", "key", ",", "val", ",", "0", ")", ".", "Err", "(", ")", "\n", "return", "err", "\n", "}" ]
//Set method of the RedisClientWrapper type
[ "Set", "method", "of", "the", "RedisClientWrapper", "type" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode0/redis_database.go#L25-L28
14,743
arschles/go-in-5-minutes
episode20/transformer.go
transform
func (t *transformer) transform(key string, fn func(string) string) bool { t.mut.Lock() defer t.mut.Unlock() val, found := t.cache[key] if !found { return false } str, ok := val.(string) if !ok { return false } newStr := fn(str) t.cache[key] = newStr return true }
go
func (t *transformer) transform(key string, fn func(string) string) bool { t.mut.Lock() defer t.mut.Unlock() val, found := t.cache[key] if !found { return false } str, ok := val.(string) if !ok { return false } newStr := fn(str) t.cache[key] = newStr return true }
[ "func", "(", "t", "*", "transformer", ")", "transform", "(", "key", "string", ",", "fn", "func", "(", "string", ")", "string", ")", "bool", "{", "t", ".", "mut", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mut", ".", "Unlock", "(", ")", "\n", "val", ",", "found", ":=", "t", ".", "cache", "[", "key", "]", "\n", "if", "!", "found", "{", "return", "false", "\n", "}", "\n", "str", ",", "ok", ":=", "val", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "newStr", ":=", "fn", "(", "str", ")", "\n", "t", ".", "cache", "[", "key", "]", "=", "newStr", "\n", "return", "true", "\n", "}" ]
// looks up key in the cache. if it exists, runs its value through fn, puts the new value // back into the cache, and returns true. otherwise does nothing and returns false
[ "looks", "up", "key", "in", "the", "cache", ".", "if", "it", "exists", "runs", "its", "value", "through", "fn", "puts", "the", "new", "value", "back", "into", "the", "cache", "and", "returns", "true", ".", "otherwise", "does", "nothing", "and", "returns", "false" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode20/transformer.go#L14-L28
14,744
arschles/go-in-5-minutes
episode20/transformer.go
remove
func (t *transformer) remove(key string) bool { t.mut.Lock() defer t.mut.Unlock() if _, found := t.cache[key]; found { delete(t.cache, key) return true } return false }
go
func (t *transformer) remove(key string) bool { t.mut.Lock() defer t.mut.Unlock() if _, found := t.cache[key]; found { delete(t.cache, key) return true } return false }
[ "func", "(", "t", "*", "transformer", ")", "remove", "(", "key", "string", ")", "bool", "{", "t", ".", "mut", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mut", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "found", ":=", "t", ".", "cache", "[", "key", "]", ";", "found", "{", "delete", "(", "t", ".", "cache", ",", "key", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// removes key from the cache if it existed and returns true. otherwise returns false
[ "removes", "key", "from", "the", "cache", "if", "it", "existed", "and", "returns", "true", ".", "otherwise", "returns", "false" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode20/transformer.go#L31-L39
14,745
arschles/go-in-5-minutes
episode15/main.go
pluralize
func pluralize(i int, singular, plural string) string { if i == 1 { return singular } return plural }
go
func pluralize(i int, singular, plural string) string { if i == 1 { return singular } return plural }
[ "func", "pluralize", "(", "i", "int", ",", "singular", ",", "plural", "string", ")", "string", "{", "if", "i", "==", "1", "{", "return", "singular", "\n", "}", "\n", "return", "plural", "\n", "}" ]
// convenience function that returns plural if i != 1, singular otherwise
[ "convenience", "function", "that", "returns", "plural", "if", "i", "!", "=", "1", "singular", "otherwise" ]
ac81bfabceea8f9293f63a4c1a7ea096f4cc085c
https://github.com/arschles/go-in-5-minutes/blob/ac81bfabceea8f9293f63a4c1a7ea096f4cc085c/episode15/main.go#L27-L32
14,746
milosgajdos83/tenus
veth_linux.go
SetPeerLinkIp
func (veth *VethPair) SetPeerLinkIp(ip net.IP, nw *net.IPNet) error { return netlink.NetworkLinkAddIp(veth.peerIfc, ip, nw) }
go
func (veth *VethPair) SetPeerLinkIp(ip net.IP, nw *net.IPNet) error { return netlink.NetworkLinkAddIp(veth.peerIfc, ip, nw) }
[ "func", "(", "veth", "*", "VethPair", ")", "SetPeerLinkIp", "(", "ip", "net", ".", "IP", ",", "nw", "*", "net", ".", "IPNet", ")", "error", "{", "return", "netlink", ".", "NetworkLinkAddIp", "(", "veth", ".", "peerIfc", ",", "ip", ",", "nw", ")", "\n", "}" ]
// SetPeerLinkIp configures peer link's IP address
[ "SetPeerLinkIp", "configures", "peer", "link", "s", "IP", "address" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/veth_linux.go#L162-L164
14,747
milosgajdos83/tenus
veth_linux.go
SetPeerLinkNsToDocker
func (veth *VethPair) SetPeerLinkNsToDocker(name string, dockerHost string) error { pid, err := DockerPidByName(name, dockerHost) if err != nil { return fmt.Errorf("Failed to find docker %s : %s", name, err) } return netlink.NetworkSetNsPid(veth.peerIfc, pid) }
go
func (veth *VethPair) SetPeerLinkNsToDocker(name string, dockerHost string) error { pid, err := DockerPidByName(name, dockerHost) if err != nil { return fmt.Errorf("Failed to find docker %s : %s", name, err) } return netlink.NetworkSetNsPid(veth.peerIfc, pid) }
[ "func", "(", "veth", "*", "VethPair", ")", "SetPeerLinkNsToDocker", "(", "name", "string", ",", "dockerHost", "string", ")", "error", "{", "pid", ",", "err", ":=", "DockerPidByName", "(", "name", ",", "dockerHost", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n\n", "return", "netlink", ".", "NetworkSetNsPid", "(", "veth", ".", "peerIfc", ",", "pid", ")", "\n", "}" ]
// SetPeerLinkNsToDocker sends peer link into Docker
[ "SetPeerLinkNsToDocker", "sends", "peer", "link", "into", "Docker" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/veth_linux.go#L167-L174
14,748
milosgajdos83/tenus
veth_linux.go
SetPeerLinkNsPid
func (veth *VethPair) SetPeerLinkNsPid(nspid int) error { return netlink.NetworkSetNsPid(veth.peerIfc, nspid) }
go
func (veth *VethPair) SetPeerLinkNsPid(nspid int) error { return netlink.NetworkSetNsPid(veth.peerIfc, nspid) }
[ "func", "(", "veth", "*", "VethPair", ")", "SetPeerLinkNsPid", "(", "nspid", "int", ")", "error", "{", "return", "netlink", ".", "NetworkSetNsPid", "(", "veth", ".", "peerIfc", ",", "nspid", ")", "\n", "}" ]
// SetPeerLinkNsPid sends peer link into container specified by PID
[ "SetPeerLinkNsPid", "sends", "peer", "link", "into", "container", "specified", "by", "PID" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/veth_linux.go#L177-L179
14,749
milosgajdos83/tenus
veth_linux.go
SetPeerLinkNsFd
func (veth *VethPair) SetPeerLinkNsFd(nspath string) error { fd, err := syscall.Open(nspath, syscall.O_RDONLY, 0) if err != nil { return fmt.Errorf("Could not attach to Network namespace: %s", err) } return netlink.NetworkSetNsFd(veth.peerIfc, fd) }
go
func (veth *VethPair) SetPeerLinkNsFd(nspath string) error { fd, err := syscall.Open(nspath, syscall.O_RDONLY, 0) if err != nil { return fmt.Errorf("Could not attach to Network namespace: %s", err) } return netlink.NetworkSetNsFd(veth.peerIfc, fd) }
[ "func", "(", "veth", "*", "VethPair", ")", "SetPeerLinkNsFd", "(", "nspath", "string", ")", "error", "{", "fd", ",", "err", ":=", "syscall", ".", "Open", "(", "nspath", ",", "syscall", ".", "O_RDONLY", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "netlink", ".", "NetworkSetNsFd", "(", "veth", ".", "peerIfc", ",", "fd", ")", "\n", "}" ]
// SetPeerLinkNsFd sends peer link into container specified by path
[ "SetPeerLinkNsFd", "sends", "peer", "link", "into", "container", "specified", "by", "path" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/veth_linux.go#L182-L189
14,750
milosgajdos83/tenus
veth_linux.go
SetPeerLinkNetInNs
func (veth *VethPair) SetPeerLinkNetInNs(nspid int, ip net.IP, network *net.IPNet, gw *net.IP) error { origNs, _ := NetNsHandle(os.Getpid()) defer syscall.Close(int(origNs)) defer system.Setns(origNs, syscall.CLONE_NEWNET) if err := SetNetNsToPid(nspid); err != nil { return fmt.Errorf("Setting network namespace failed: %s", err) } if err := netlink.NetworkLinkAddIp(veth.peerIfc, ip, network); err != nil { return fmt.Errorf("Unable to set IP: %s in pid: %d network namespace", ip.String(), nspid) } if err := netlink.NetworkLinkUp(veth.peerIfc); err != nil { return fmt.Errorf("Unable to bring %s interface UP: %s", veth.peerIfc.Name, nspid) } if gw != nil { if err := netlink.AddDefaultGw(gw.String(), veth.peerIfc.Name); err != nil { return fmt.Errorf("Unable to set Default gateway: %s in pid: %d network namespace", gw.String(), nspid) } } return nil }
go
func (veth *VethPair) SetPeerLinkNetInNs(nspid int, ip net.IP, network *net.IPNet, gw *net.IP) error { origNs, _ := NetNsHandle(os.Getpid()) defer syscall.Close(int(origNs)) defer system.Setns(origNs, syscall.CLONE_NEWNET) if err := SetNetNsToPid(nspid); err != nil { return fmt.Errorf("Setting network namespace failed: %s", err) } if err := netlink.NetworkLinkAddIp(veth.peerIfc, ip, network); err != nil { return fmt.Errorf("Unable to set IP: %s in pid: %d network namespace", ip.String(), nspid) } if err := netlink.NetworkLinkUp(veth.peerIfc); err != nil { return fmt.Errorf("Unable to bring %s interface UP: %s", veth.peerIfc.Name, nspid) } if gw != nil { if err := netlink.AddDefaultGw(gw.String(), veth.peerIfc.Name); err != nil { return fmt.Errorf("Unable to set Default gateway: %s in pid: %d network namespace", gw.String(), nspid) } } return nil }
[ "func", "(", "veth", "*", "VethPair", ")", "SetPeerLinkNetInNs", "(", "nspid", "int", ",", "ip", "net", ".", "IP", ",", "network", "*", "net", ".", "IPNet", ",", "gw", "*", "net", ".", "IP", ")", "error", "{", "origNs", ",", "_", ":=", "NetNsHandle", "(", "os", ".", "Getpid", "(", ")", ")", "\n", "defer", "syscall", ".", "Close", "(", "int", "(", "origNs", ")", ")", "\n", "defer", "system", ".", "Setns", "(", "origNs", ",", "syscall", ".", "CLONE_NEWNET", ")", "\n\n", "if", "err", ":=", "SetNetNsToPid", "(", "nspid", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "netlink", ".", "NetworkLinkAddIp", "(", "veth", ".", "peerIfc", ",", "ip", ",", "network", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ip", ".", "String", "(", ")", ",", "nspid", ")", "\n", "}", "\n\n", "if", "err", ":=", "netlink", ".", "NetworkLinkUp", "(", "veth", ".", "peerIfc", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "veth", ".", "peerIfc", ".", "Name", ",", "nspid", ")", "\n", "}", "\n\n", "if", "gw", "!=", "nil", "{", "if", "err", ":=", "netlink", ".", "AddDefaultGw", "(", "gw", ".", "String", "(", ")", ",", "veth", ".", "peerIfc", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "gw", ".", "String", "(", ")", ",", "nspid", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetPeerLinkNetInNs configures peer link's IP network in network namespace specified by PID
[ "SetPeerLinkNetInNs", "configures", "peer", "link", "s", "IP", "network", "in", "network", "namespace", "specified", "by", "PID" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/veth_linux.go#L192-L216
14,751
milosgajdos83/tenus
helpers_linux.go
makeNetInterfaceName
func makeNetInterfaceName(base string) string { for { name := base + randomString(6) if _, err := net.InterfaceByName(name); err == nil { continue } return name } }
go
func makeNetInterfaceName(base string) string { for { name := base + randomString(6) if _, err := net.InterfaceByName(name); err == nil { continue } return name } }
[ "func", "makeNetInterfaceName", "(", "base", "string", ")", "string", "{", "for", "{", "name", ":=", "base", "+", "randomString", "(", "6", ")", "\n", "if", "_", ",", "err", ":=", "net", ".", "InterfaceByName", "(", "name", ")", ";", "err", "==", "nil", "{", "continue", "\n", "}", "\n\n", "return", "name", "\n", "}", "\n", "}" ]
// generates new unused network interfaces name with given prefix
[ "generates", "new", "unused", "network", "interfaces", "name", "with", "given", "prefix" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/helpers_linux.go#L41-L50
14,752
milosgajdos83/tenus
helpers_linux.go
validMacAddress
func validMacAddress(macaddr string) error { if _, err := net.ParseMAC(macaddr); err != nil { return fmt.Errorf("Can not parse MAC address: %s", err) } if _, err := FindInterfaceByMacAddress(macaddr); err == nil { return fmt.Errorf("MAC Address already assigned on the host: %s", macaddr) } return nil }
go
func validMacAddress(macaddr string) error { if _, err := net.ParseMAC(macaddr); err != nil { return fmt.Errorf("Can not parse MAC address: %s", err) } if _, err := FindInterfaceByMacAddress(macaddr); err == nil { return fmt.Errorf("MAC Address already assigned on the host: %s", macaddr) } return nil }
[ "func", "validMacAddress", "(", "macaddr", "string", ")", "error", "{", "if", "_", ",", "err", ":=", "net", ".", "ParseMAC", "(", "macaddr", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "FindInterfaceByMacAddress", "(", "macaddr", ")", ";", "err", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "macaddr", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validates MacAddress LinkOption
[ "validates", "MacAddress", "LinkOption" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/helpers_linux.go#L62-L72
14,753
milosgajdos83/tenus
helpers_linux.go
validFlags
func validFlags(flags net.Flags) error { if (flags & syscall.IFF_UP) != syscall.IFF_UP { return fmt.Errorf("Unsupported network flags specified: %v", flags) } return nil }
go
func validFlags(flags net.Flags) error { if (flags & syscall.IFF_UP) != syscall.IFF_UP { return fmt.Errorf("Unsupported network flags specified: %v", flags) } return nil }
[ "func", "validFlags", "(", "flags", "net", ".", "Flags", ")", "error", "{", "if", "(", "flags", "&", "syscall", ".", "IFF_UP", ")", "!=", "syscall", ".", "IFF_UP", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "flags", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validates Flags LinkOption
[ "validates", "Flags", "LinkOption" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/helpers_linux.go#L84-L90
14,754
milosgajdos83/tenus
helpers_linux.go
NetInterfaceNameValid
func NetInterfaceNameValid(name string) (bool, error) { if name == "" { return false, errors.New("Interface name can not be empty") } if len(name) == 1 { return false, fmt.Errorf("Interface name too short: %s", name) } if len(name) > netlink.IFNAMSIZ { return false, fmt.Errorf("Interface name too long: %s", name) } for _, char := range name { if unicode.IsSpace(char) || char > 0x7F { return false, fmt.Errorf("Invalid characters in interface name: %s", name) } } return true, nil }
go
func NetInterfaceNameValid(name string) (bool, error) { if name == "" { return false, errors.New("Interface name can not be empty") } if len(name) == 1 { return false, fmt.Errorf("Interface name too short: %s", name) } if len(name) > netlink.IFNAMSIZ { return false, fmt.Errorf("Interface name too long: %s", name) } for _, char := range name { if unicode.IsSpace(char) || char > 0x7F { return false, fmt.Errorf("Invalid characters in interface name: %s", name) } } return true, nil }
[ "func", "NetInterfaceNameValid", "(", "name", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "name", "==", "\"", "\"", "{", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "name", ")", "==", "1", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "if", "len", "(", "name", ")", ">", "netlink", ".", "IFNAMSIZ", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "for", "_", ",", "char", ":=", "range", "name", "{", "if", "unicode", ".", "IsSpace", "(", "char", ")", "||", "char", ">", "0x7F", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// NetInterfaceNameValid checks if the network interface name is valid. // It accepts interface name as a string. It returns error if invalid interface name is supplied.
[ "NetInterfaceNameValid", "checks", "if", "the", "network", "interface", "name", "is", "valid", ".", "It", "accepts", "interface", "name", "as", "a", "string", ".", "It", "returns", "error", "if", "invalid", "interface", "name", "is", "supplied", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/helpers_linux.go#L94-L114
14,755
milosgajdos83/tenus
helpers_linux.go
NetNsHandle
func NetNsHandle(nspid int) (uintptr, error) { if nspid <= 0 || nspid == 1 { return 0, fmt.Errorf("Incorred PID specified: %d", nspid) } nsPath := path.Join("/", "proc", strconv.Itoa(nspid), "ns/net") if nsPath == "" { return 0, fmt.Errorf("Could not find Network namespace for pid: %d", nspid) } file, err := os.Open(nsPath) if err != nil { return 0, fmt.Errorf("Could not open Network Namespace: %s", err) } return file.Fd(), nil }
go
func NetNsHandle(nspid int) (uintptr, error) { if nspid <= 0 || nspid == 1 { return 0, fmt.Errorf("Incorred PID specified: %d", nspid) } nsPath := path.Join("/", "proc", strconv.Itoa(nspid), "ns/net") if nsPath == "" { return 0, fmt.Errorf("Could not find Network namespace for pid: %d", nspid) } file, err := os.Open(nsPath) if err != nil { return 0, fmt.Errorf("Could not open Network Namespace: %s", err) } return file.Fd(), nil }
[ "func", "NetNsHandle", "(", "nspid", "int", ")", "(", "uintptr", ",", "error", ")", "{", "if", "nspid", "<=", "0", "||", "nspid", "==", "1", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "nspid", ")", "\n", "}", "\n\n", "nsPath", ":=", "path", ".", "Join", "(", "\"", "\"", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "nspid", ")", ",", "\"", "\"", ")", "\n", "if", "nsPath", "==", "\"", "\"", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "nspid", ")", "\n", "}", "\n\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "nsPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "file", ".", "Fd", "(", ")", ",", "nil", "\n", "}" ]
// NetNsHandle returns a file descriptor handle for network namespace specified by PID. // It returns error if network namespace could not be found or if network namespace path could not be opened.
[ "NetNsHandle", "returns", "a", "file", "descriptor", "handle", "for", "network", "namespace", "specified", "by", "PID", ".", "It", "returns", "error", "if", "network", "namespace", "could", "not", "be", "found", "or", "if", "network", "namespace", "path", "could", "not", "be", "opened", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/helpers_linux.go#L206-L222
14,756
milosgajdos83/tenus
helpers_linux.go
SetNetNsToPid
func SetNetNsToPid(nspid int) error { if nspid <= 0 || nspid == 1 { return fmt.Errorf("Incorred PID specified: %d", nspid) } nsFd, err := NetNsHandle(nspid) defer syscall.Close(int(nsFd)) if err != nil { return fmt.Errorf("Could not get network namespace handle: %s", err) } if err := system.Setns(nsFd, syscall.CLONE_NEWNET); err != nil { return fmt.Errorf("Unable to set the network namespace: %v", err) } return nil }
go
func SetNetNsToPid(nspid int) error { if nspid <= 0 || nspid == 1 { return fmt.Errorf("Incorred PID specified: %d", nspid) } nsFd, err := NetNsHandle(nspid) defer syscall.Close(int(nsFd)) if err != nil { return fmt.Errorf("Could not get network namespace handle: %s", err) } if err := system.Setns(nsFd, syscall.CLONE_NEWNET); err != nil { return fmt.Errorf("Unable to set the network namespace: %v", err) } return nil }
[ "func", "SetNetNsToPid", "(", "nspid", "int", ")", "error", "{", "if", "nspid", "<=", "0", "||", "nspid", "==", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "nspid", ")", "\n", "}", "\n\n", "nsFd", ",", "err", ":=", "NetNsHandle", "(", "nspid", ")", "\n", "defer", "syscall", ".", "Close", "(", "int", "(", "nsFd", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "system", ".", "Setns", "(", "nsFd", ",", "syscall", ".", "CLONE_NEWNET", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetNetNsToPid sets network namespace to the one specied by PID. // It returns error if the network namespace could not be set.
[ "SetNetNsToPid", "sets", "network", "namespace", "to", "the", "one", "specied", "by", "PID", ".", "It", "returns", "error", "if", "the", "network", "namespace", "could", "not", "be", "set", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/helpers_linux.go#L226-L242
14,757
milosgajdos83/tenus
bridge_linux.go
BridgeFromName
func BridgeFromName(ifcName string) (Bridger, error) { if ok, err := NetInterfaceNameValid(ifcName); !ok { return nil, err } newIfc, err := net.InterfaceByName(ifcName) if err != nil { return nil, fmt.Errorf("Could not find the new interface: %s", err) } return &Bridge{ Link: Link{ ifc: newIfc, }, }, nil }
go
func BridgeFromName(ifcName string) (Bridger, error) { if ok, err := NetInterfaceNameValid(ifcName); !ok { return nil, err } newIfc, err := net.InterfaceByName(ifcName) if err != nil { return nil, fmt.Errorf("Could not find the new interface: %s", err) } return &Bridge{ Link: Link{ ifc: newIfc, }, }, nil }
[ "func", "BridgeFromName", "(", "ifcName", "string", ")", "(", "Bridger", ",", "error", ")", "{", "if", "ok", ",", "err", ":=", "NetInterfaceNameValid", "(", "ifcName", ")", ";", "!", "ok", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "newIfc", ",", "err", ":=", "net", ".", "InterfaceByName", "(", "ifcName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "&", "Bridge", "{", "Link", ":", "Link", "{", "ifc", ":", "newIfc", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// BridgeFromName returns a tenus network bridge from an existing bridge of given name on the Linux host. // It returns error if the bridge of the given name cannot be found.
[ "BridgeFromName", "returns", "a", "tenus", "network", "bridge", "from", "an", "existing", "bridge", "of", "given", "name", "on", "the", "Linux", "host", ".", "It", "returns", "error", "if", "the", "bridge", "of", "the", "given", "name", "cannot", "be", "found", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/bridge_linux.go#L92-L107
14,758
milosgajdos83/tenus
link_linux.go
NewLinkFrom
func NewLinkFrom(ifcName string) (Linker, error) { if ok, err := NetInterfaceNameValid(ifcName); !ok { return nil, err } newIfc, err := net.InterfaceByName(ifcName) if err != nil { return nil, fmt.Errorf("Could not find the new interface: %s", err) } return &Link{ ifc: newIfc, }, nil }
go
func NewLinkFrom(ifcName string) (Linker, error) { if ok, err := NetInterfaceNameValid(ifcName); !ok { return nil, err } newIfc, err := net.InterfaceByName(ifcName) if err != nil { return nil, fmt.Errorf("Could not find the new interface: %s", err) } return &Link{ ifc: newIfc, }, nil }
[ "func", "NewLinkFrom", "(", "ifcName", "string", ")", "(", "Linker", ",", "error", ")", "{", "if", "ok", ",", "err", ":=", "NetInterfaceNameValid", "(", "ifcName", ")", ";", "!", "ok", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "newIfc", ",", "err", ":=", "net", ".", "InterfaceByName", "(", "ifcName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "&", "Link", "{", "ifc", ":", "newIfc", ",", "}", ",", "nil", "\n", "}" ]
// NewLinkFrom creates new tenus link on Linux host from an existing interface of given name
[ "NewLinkFrom", "creates", "new", "tenus", "link", "on", "Linux", "host", "from", "an", "existing", "interface", "of", "given", "name" ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/link_linux.go#L86-L99
14,759
milosgajdos83/tenus
link_linux.go
SetLinkNetNsPid
func (l *Link) SetLinkNetNsPid(nspid int) error { return netlink.NetworkSetNsPid(l.NetInterface(), nspid) }
go
func (l *Link) SetLinkNetNsPid(nspid int) error { return netlink.NetworkSetNsPid(l.NetInterface(), nspid) }
[ "func", "(", "l", "*", "Link", ")", "SetLinkNetNsPid", "(", "nspid", "int", ")", "error", "{", "return", "netlink", ".", "NetworkSetNsPid", "(", "l", ".", "NetInterface", "(", ")", ",", "nspid", ")", "\n", "}" ]
// SetLinkNetNsPid moves the link to Network namespace specified by PID.
[ "SetLinkNetNsPid", "moves", "the", "link", "to", "Network", "namespace", "specified", "by", "PID", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/link_linux.go#L208-L210
14,760
milosgajdos83/tenus
link_linux.go
SetLinkNetInNs
func (l *Link) SetLinkNetInNs(nspid int, ip net.IP, network *net.IPNet, gw *net.IP) error { origNs, _ := NetNsHandle(os.Getpid()) defer syscall.Close(int(origNs)) defer system.Setns(origNs, syscall.CLONE_NEWNET) if err := SetNetNsToPid(nspid); err != nil { return fmt.Errorf("Setting network namespace failed: %s", err) } if err := netlink.NetworkLinkAddIp(l.NetInterface(), ip, network); err != nil { return fmt.Errorf("Unable to set IP: %s in pid: %d network namespace", ip.String(), nspid) } if err := netlink.NetworkLinkUp(l.ifc); err != nil { return fmt.Errorf("Unable to bring %s interface UP: %s", l.ifc.Name, nspid) } if gw != nil { if err := netlink.AddDefaultGw(gw.String(), l.NetInterface().Name); err != nil { return fmt.Errorf("Unable to set Default gateway: %s in pid: %d network namespace", gw.String(), nspid) } } return nil }
go
func (l *Link) SetLinkNetInNs(nspid int, ip net.IP, network *net.IPNet, gw *net.IP) error { origNs, _ := NetNsHandle(os.Getpid()) defer syscall.Close(int(origNs)) defer system.Setns(origNs, syscall.CLONE_NEWNET) if err := SetNetNsToPid(nspid); err != nil { return fmt.Errorf("Setting network namespace failed: %s", err) } if err := netlink.NetworkLinkAddIp(l.NetInterface(), ip, network); err != nil { return fmt.Errorf("Unable to set IP: %s in pid: %d network namespace", ip.String(), nspid) } if err := netlink.NetworkLinkUp(l.ifc); err != nil { return fmt.Errorf("Unable to bring %s interface UP: %s", l.ifc.Name, nspid) } if gw != nil { if err := netlink.AddDefaultGw(gw.String(), l.NetInterface().Name); err != nil { return fmt.Errorf("Unable to set Default gateway: %s in pid: %d network namespace", gw.String(), nspid) } } return nil }
[ "func", "(", "l", "*", "Link", ")", "SetLinkNetInNs", "(", "nspid", "int", ",", "ip", "net", ".", "IP", ",", "network", "*", "net", ".", "IPNet", ",", "gw", "*", "net", ".", "IP", ")", "error", "{", "origNs", ",", "_", ":=", "NetNsHandle", "(", "os", ".", "Getpid", "(", ")", ")", "\n", "defer", "syscall", ".", "Close", "(", "int", "(", "origNs", ")", ")", "\n", "defer", "system", ".", "Setns", "(", "origNs", ",", "syscall", ".", "CLONE_NEWNET", ")", "\n\n", "if", "err", ":=", "SetNetNsToPid", "(", "nspid", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "netlink", ".", "NetworkLinkAddIp", "(", "l", ".", "NetInterface", "(", ")", ",", "ip", ",", "network", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ip", ".", "String", "(", ")", ",", "nspid", ")", "\n", "}", "\n\n", "if", "err", ":=", "netlink", ".", "NetworkLinkUp", "(", "l", ".", "ifc", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ".", "ifc", ".", "Name", ",", "nspid", ")", "\n", "}", "\n\n", "if", "gw", "!=", "nil", "{", "if", "err", ":=", "netlink", ".", "AddDefaultGw", "(", "gw", ".", "String", "(", ")", ",", "l", ".", "NetInterface", "(", ")", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "gw", ".", "String", "(", ")", ",", "nspid", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetLinkNetInNs configures network settings of the link in network namespace specified by PID.
[ "SetLinkNetInNs", "configures", "network", "settings", "of", "the", "link", "in", "network", "namespace", "specified", "by", "PID", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/link_linux.go#L213-L237
14,761
milosgajdos83/tenus
link_linux.go
SetLinkNsFd
func (l *Link) SetLinkNsFd(nspath string) error { fd, err := syscall.Open(nspath, syscall.O_RDONLY, 0) if err != nil { return fmt.Errorf("Could not attach to Network namespace: %s", err) } return netlink.NetworkSetNsFd(l.NetInterface(), fd) }
go
func (l *Link) SetLinkNsFd(nspath string) error { fd, err := syscall.Open(nspath, syscall.O_RDONLY, 0) if err != nil { return fmt.Errorf("Could not attach to Network namespace: %s", err) } return netlink.NetworkSetNsFd(l.NetInterface(), fd) }
[ "func", "(", "l", "*", "Link", ")", "SetLinkNsFd", "(", "nspath", "string", ")", "error", "{", "fd", ",", "err", ":=", "syscall", ".", "Open", "(", "nspath", ",", "syscall", ".", "O_RDONLY", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "netlink", ".", "NetworkSetNsFd", "(", "l", ".", "NetInterface", "(", ")", ",", "fd", ")", "\n", "}" ]
// SetLinkNsFd sets the link's Linux namespace to the one specified by filesystem path.
[ "SetLinkNsFd", "sets", "the", "link", "s", "Linux", "namespace", "to", "the", "one", "specified", "by", "filesystem", "path", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/link_linux.go#L240-L247
14,762
milosgajdos83/tenus
link_linux.go
SetLinkNsToDocker
func (l *Link) SetLinkNsToDocker(name string, dockerHost string) error { pid, err := DockerPidByName(name, dockerHost) if err != nil { return fmt.Errorf("Failed to find docker %s : %s", name, err) } return l.SetLinkNetNsPid(pid) }
go
func (l *Link) SetLinkNsToDocker(name string, dockerHost string) error { pid, err := DockerPidByName(name, dockerHost) if err != nil { return fmt.Errorf("Failed to find docker %s : %s", name, err) } return l.SetLinkNetNsPid(pid) }
[ "func", "(", "l", "*", "Link", ")", "SetLinkNsToDocker", "(", "name", "string", ",", "dockerHost", "string", ")", "error", "{", "pid", ",", "err", ":=", "DockerPidByName", "(", "name", ",", "dockerHost", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n\n", "return", "l", ".", "SetLinkNetNsPid", "(", "pid", ")", "\n", "}" ]
// SetLinkNsToDocker sets the link's Linux namespace to a running Docker one specified by Docker name.
[ "SetLinkNsToDocker", "sets", "the", "link", "s", "Linux", "namespace", "to", "a", "running", "Docker", "one", "specified", "by", "Docker", "name", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/link_linux.go#L250-L257
14,763
milosgajdos83/tenus
link_linux.go
RenameInterfaceByName
func RenameInterfaceByName(old string, newName string) error { iface, err := net.InterfaceByName(old) if err != nil { return err } return netlink.NetworkChangeName(iface, newName) }
go
func RenameInterfaceByName(old string, newName string) error { iface, err := net.InterfaceByName(old) if err != nil { return err } return netlink.NetworkChangeName(iface, newName) }
[ "func", "RenameInterfaceByName", "(", "old", "string", ",", "newName", "string", ")", "error", "{", "iface", ",", "err", ":=", "net", ".", "InterfaceByName", "(", "old", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "netlink", ".", "NetworkChangeName", "(", "iface", ",", "newName", ")", "\n", "}" ]
// RenameInterfaceByName renames an interface of given name.
[ "RenameInterfaceByName", "renames", "an", "interface", "of", "given", "name", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/link_linux.go#L260-L266
14,764
milosgajdos83/tenus
link_linux.go
setLinkOptions
func setLinkOptions(ifc *net.Interface, opts LinkOptions) error { macaddr, mtu, flags, ns := opts.MacAddr, opts.MTU, opts.Flags, opts.Ns // if MTU is passed in LinkOptions if mtu != 0 { if err := validMtu(mtu); err != nil { return err } if err := netlink.NetworkSetMTU(ifc, mtu); err != nil { return fmt.Errorf("Unable to set MTU: %s", err) } } // if MacAddress is passed in LinkOptions if macaddr != "" { if err := validMacAddress(macaddr); err != nil { return err } if err := netlink.NetworkSetMacAddress(ifc, macaddr); err != nil { return fmt.Errorf("Unable to set MAC Address: %s", err) } } // if ns is passed in LinkOptions if ns != 0 { if err := validNs(ns); err != nil { return err } if err := netlink.NetworkSetNsPid(ifc, ns); err != nil { return fmt.Errorf("Unable to set Network namespace: %s", err) } } // if flags is passed in LinkOptions if flags != 0 { if err := validFlags(flags); err != nil { return err } if ns != 0 && (ns != 1 || ns != os.Getpid()) { if (flags & syscall.IFF_UP) == syscall.IFF_UP { origNs, _ := NetNsHandle(os.Getpid()) defer syscall.Close(int(origNs)) defer system.Setns(origNs, syscall.CLONE_NEWNET) if err := SetNetNsToPid(ns); err != nil { return fmt.Errorf("Switching to %d network namespace failed: %s", ns, err) } if err := netlink.NetworkLinkUp(ifc); err != nil { return fmt.Errorf("Unable to bring %s interface UP: %s", ifc.Name, ns) } } } else { if err := netlink.NetworkLinkUp(ifc); err != nil { return fmt.Errorf("Could not bring up network link %s: %s", ifc.Name, err) } } } return nil }
go
func setLinkOptions(ifc *net.Interface, opts LinkOptions) error { macaddr, mtu, flags, ns := opts.MacAddr, opts.MTU, opts.Flags, opts.Ns // if MTU is passed in LinkOptions if mtu != 0 { if err := validMtu(mtu); err != nil { return err } if err := netlink.NetworkSetMTU(ifc, mtu); err != nil { return fmt.Errorf("Unable to set MTU: %s", err) } } // if MacAddress is passed in LinkOptions if macaddr != "" { if err := validMacAddress(macaddr); err != nil { return err } if err := netlink.NetworkSetMacAddress(ifc, macaddr); err != nil { return fmt.Errorf("Unable to set MAC Address: %s", err) } } // if ns is passed in LinkOptions if ns != 0 { if err := validNs(ns); err != nil { return err } if err := netlink.NetworkSetNsPid(ifc, ns); err != nil { return fmt.Errorf("Unable to set Network namespace: %s", err) } } // if flags is passed in LinkOptions if flags != 0 { if err := validFlags(flags); err != nil { return err } if ns != 0 && (ns != 1 || ns != os.Getpid()) { if (flags & syscall.IFF_UP) == syscall.IFF_UP { origNs, _ := NetNsHandle(os.Getpid()) defer syscall.Close(int(origNs)) defer system.Setns(origNs, syscall.CLONE_NEWNET) if err := SetNetNsToPid(ns); err != nil { return fmt.Errorf("Switching to %d network namespace failed: %s", ns, err) } if err := netlink.NetworkLinkUp(ifc); err != nil { return fmt.Errorf("Unable to bring %s interface UP: %s", ifc.Name, ns) } } } else { if err := netlink.NetworkLinkUp(ifc); err != nil { return fmt.Errorf("Could not bring up network link %s: %s", ifc.Name, err) } } } return nil }
[ "func", "setLinkOptions", "(", "ifc", "*", "net", ".", "Interface", ",", "opts", "LinkOptions", ")", "error", "{", "macaddr", ",", "mtu", ",", "flags", ",", "ns", ":=", "opts", ".", "MacAddr", ",", "opts", ".", "MTU", ",", "opts", ".", "Flags", ",", "opts", ".", "Ns", "\n\n", "// if MTU is passed in LinkOptions", "if", "mtu", "!=", "0", "{", "if", "err", ":=", "validMtu", "(", "mtu", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "netlink", ".", "NetworkSetMTU", "(", "ifc", ",", "mtu", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// if MacAddress is passed in LinkOptions", "if", "macaddr", "!=", "\"", "\"", "{", "if", "err", ":=", "validMacAddress", "(", "macaddr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "netlink", ".", "NetworkSetMacAddress", "(", "ifc", ",", "macaddr", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// if ns is passed in LinkOptions", "if", "ns", "!=", "0", "{", "if", "err", ":=", "validNs", "(", "ns", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "netlink", ".", "NetworkSetNsPid", "(", "ifc", ",", "ns", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// if flags is passed in LinkOptions", "if", "flags", "!=", "0", "{", "if", "err", ":=", "validFlags", "(", "flags", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "ns", "!=", "0", "&&", "(", "ns", "!=", "1", "||", "ns", "!=", "os", ".", "Getpid", "(", ")", ")", "{", "if", "(", "flags", "&", "syscall", ".", "IFF_UP", ")", "==", "syscall", ".", "IFF_UP", "{", "origNs", ",", "_", ":=", "NetNsHandle", "(", "os", ".", "Getpid", "(", ")", ")", "\n", "defer", "syscall", ".", "Close", "(", "int", "(", "origNs", ")", ")", "\n", "defer", "system", ".", "Setns", "(", "origNs", ",", "syscall", ".", "CLONE_NEWNET", ")", "\n\n", "if", "err", ":=", "SetNetNsToPid", "(", "ns", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ns", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "netlink", ".", "NetworkLinkUp", "(", "ifc", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ifc", ".", "Name", ",", "ns", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "netlink", ".", "NetworkLinkUp", "(", "ifc", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ifc", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// setLinkOptions validates and sets link's various options passed in as LinkOptions.
[ "setLinkOptions", "validates", "and", "sets", "link", "s", "various", "options", "passed", "in", "as", "LinkOptions", "." ]
1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b
https://github.com/milosgajdos83/tenus/blob/1f3ed00ae7d84ecdd97a628d26551590f5a3ab4b/link_linux.go#L269-L333
14,765
go-gremlin/gremlin
connection.go
ExecQuery
func (c *Client) ExecQuery(query string) ([]byte, error) { req := Query(query) return c.Exec(req) }
go
func (c *Client) ExecQuery(query string) ([]byte, error) { req := Query(query) return c.Exec(req) }
[ "func", "(", "c", "*", "Client", ")", "ExecQuery", "(", "query", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "req", ":=", "Query", "(", "query", ")", "\n", "return", "c", ".", "Exec", "(", "req", ")", "\n", "}" ]
// Client executes the provided request
[ "Client", "executes", "the", "provided", "request" ]
0036b9fca17fe60367221cd043525a688ae8b3ea
https://github.com/go-gremlin/gremlin/blob/0036b9fca17fe60367221cd043525a688ae8b3ea/connection.go#L38-L41
14,766
go-gremlin/gremlin
connection.go
NewAuthInfo
func NewAuthInfo(options ...OptAuth) (*AuthInfo, error) { auth := &AuthInfo{} for _, op := range options { err := op(auth) if err != nil { return nil, err } } return auth, nil }
go
func NewAuthInfo(options ...OptAuth) (*AuthInfo, error) { auth := &AuthInfo{} for _, op := range options { err := op(auth) if err != nil { return nil, err } } return auth, nil }
[ "func", "NewAuthInfo", "(", "options", "...", "OptAuth", ")", "(", "*", "AuthInfo", ",", "error", ")", "{", "auth", ":=", "&", "AuthInfo", "{", "}", "\n", "for", "_", ",", "op", ":=", "range", "options", "{", "err", ":=", "op", "(", "auth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "auth", ",", "nil", "\n", "}" ]
// Constructor for different authentication possibilities
[ "Constructor", "for", "different", "authentication", "possibilities" ]
0036b9fca17fe60367221cd043525a688ae8b3ea
https://github.com/go-gremlin/gremlin/blob/0036b9fca17fe60367221cd043525a688ae8b3ea/connection.go#L121-L130
14,767
go-gremlin/gremlin
connection.go
OptAuthEnv
func OptAuthEnv() OptAuth { return func(auth *AuthInfo) error { user, ok := os.LookupEnv("GREMLIN_USER") if !ok { return errors.New("Variable GREMLIN_USER is not set") } pass, ok := os.LookupEnv("GREMLIN_PASS") if !ok { return errors.New("Variable GREMLIN_PASS is not set") } auth.User = user auth.Pass = pass return nil } }
go
func OptAuthEnv() OptAuth { return func(auth *AuthInfo) error { user, ok := os.LookupEnv("GREMLIN_USER") if !ok { return errors.New("Variable GREMLIN_USER is not set") } pass, ok := os.LookupEnv("GREMLIN_PASS") if !ok { return errors.New("Variable GREMLIN_PASS is not set") } auth.User = user auth.Pass = pass return nil } }
[ "func", "OptAuthEnv", "(", ")", "OptAuth", "{", "return", "func", "(", "auth", "*", "AuthInfo", ")", "error", "{", "user", ",", "ok", ":=", "os", ".", "LookupEnv", "(", "\"", "\"", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "pass", ",", "ok", ":=", "os", ".", "LookupEnv", "(", "\"", "\"", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "auth", ".", "User", "=", "user", "\n", "auth", ".", "Pass", "=", "pass", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Sets authentication info from environment variables GREMLIN_USER and GREMLIN_PASS
[ "Sets", "authentication", "info", "from", "environment", "variables", "GREMLIN_USER", "and", "GREMLIN_PASS" ]
0036b9fca17fe60367221cd043525a688ae8b3ea
https://github.com/go-gremlin/gremlin/blob/0036b9fca17fe60367221cd043525a688ae8b3ea/connection.go#L133-L147
14,768
go-gremlin/gremlin
connection.go
OptAuthUserPass
func OptAuthUserPass(user, pass string) OptAuth { return func(auth *AuthInfo) error { auth.User = user auth.Pass = pass return nil } }
go
func OptAuthUserPass(user, pass string) OptAuth { return func(auth *AuthInfo) error { auth.User = user auth.Pass = pass return nil } }
[ "func", "OptAuthUserPass", "(", "user", ",", "pass", "string", ")", "OptAuth", "{", "return", "func", "(", "auth", "*", "AuthInfo", ")", "error", "{", "auth", ".", "User", "=", "user", "\n", "auth", ".", "Pass", "=", "pass", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Sets authentication information from username and password
[ "Sets", "authentication", "information", "from", "username", "and", "password" ]
0036b9fca17fe60367221cd043525a688ae8b3ea
https://github.com/go-gremlin/gremlin/blob/0036b9fca17fe60367221cd043525a688ae8b3ea/connection.go#L150-L156
14,769
go-gremlin/gremlin
connection.go
Authenticate
func (c *Client) Authenticate(requestId string) ([]byte, error) { auth, err := NewAuthInfo(c.Auth...) if err != nil { return nil, err } var sasl []byte sasl = append(sasl, 0) sasl = append(sasl, []byte(auth.User)...) sasl = append(sasl, 0) sasl = append(sasl, []byte(auth.Pass)...) saslEnc := base64.StdEncoding.EncodeToString(sasl) args := &RequestArgs{Sasl: saslEnc} authReq := &Request{ RequestId: requestId, Processor: "trasversal", Op: "authentication", Args: args, } return c.Exec(authReq) }
go
func (c *Client) Authenticate(requestId string) ([]byte, error) { auth, err := NewAuthInfo(c.Auth...) if err != nil { return nil, err } var sasl []byte sasl = append(sasl, 0) sasl = append(sasl, []byte(auth.User)...) sasl = append(sasl, 0) sasl = append(sasl, []byte(auth.Pass)...) saslEnc := base64.StdEncoding.EncodeToString(sasl) args := &RequestArgs{Sasl: saslEnc} authReq := &Request{ RequestId: requestId, Processor: "trasversal", Op: "authentication", Args: args, } return c.Exec(authReq) }
[ "func", "(", "c", "*", "Client", ")", "Authenticate", "(", "requestId", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "auth", ",", "err", ":=", "NewAuthInfo", "(", "c", ".", "Auth", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "sasl", "[", "]", "byte", "\n", "sasl", "=", "append", "(", "sasl", ",", "0", ")", "\n", "sasl", "=", "append", "(", "sasl", ",", "[", "]", "byte", "(", "auth", ".", "User", ")", "...", ")", "\n", "sasl", "=", "append", "(", "sasl", ",", "0", ")", "\n", "sasl", "=", "append", "(", "sasl", ",", "[", "]", "byte", "(", "auth", ".", "Pass", ")", "...", ")", "\n", "saslEnc", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "sasl", ")", "\n", "args", ":=", "&", "RequestArgs", "{", "Sasl", ":", "saslEnc", "}", "\n", "authReq", ":=", "&", "Request", "{", "RequestId", ":", "requestId", ",", "Processor", ":", "\"", "\"", ",", "Op", ":", "\"", "\"", ",", "Args", ":", "args", ",", "}", "\n", "return", "c", ".", "Exec", "(", "authReq", ")", "\n", "}" ]
// Authenticates the connection
[ "Authenticates", "the", "connection" ]
0036b9fca17fe60367221cd043525a688ae8b3ea
https://github.com/go-gremlin/gremlin/blob/0036b9fca17fe60367221cd043525a688ae8b3ea/connection.go#L159-L178
14,770
go-gremlin/gremlin
response.go
String
func (r Response) String() string { return fmt.Sprintf("Response \nRequestId: %v, \nStatus: {%#v}, \nResult: {%#v}\n", r.RequestId, r.Status, r.Result) }
go
func (r Response) String() string { return fmt.Sprintf("Response \nRequestId: %v, \nStatus: {%#v}, \nResult: {%#v}\n", r.RequestId, r.Status, r.Result) }
[ "func", "(", "r", "Response", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\\n", "\"", ",", "r", ".", "RequestId", ",", "r", ".", "Status", ",", "r", ".", "Result", ")", "\n", "}" ]
// Implementation of the stringer interface. Useful for exploration
[ "Implementation", "of", "the", "stringer", "interface", ".", "Useful", "for", "exploration" ]
0036b9fca17fe60367221cd043525a688ae8b3ea
https://github.com/go-gremlin/gremlin/blob/0036b9fca17fe60367221cd043525a688ae8b3ea/response.go#L26-L28
14,771
Coccodrillo/apns
mock_feedback_server.go
StartMockFeedbackServer
func StartMockFeedbackServer(certFile, keyFile string) { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { log.Panic(err) } config := tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert} log.Print("- starting Mock Apple Feedback TCP server at 0.0.0.0:5555") srv, _ := tls.Listen("tcp", "0.0.0.0:5555", &config) for { conn, err := srv.Accept() if err != nil { log.Panic(err) } go loop(conn) } }
go
func StartMockFeedbackServer(certFile, keyFile string) { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { log.Panic(err) } config := tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert} log.Print("- starting Mock Apple Feedback TCP server at 0.0.0.0:5555") srv, _ := tls.Listen("tcp", "0.0.0.0:5555", &config) for { conn, err := srv.Accept() if err != nil { log.Panic(err) } go loop(conn) } }
[ "func", "StartMockFeedbackServer", "(", "certFile", ",", "keyFile", "string", ")", "{", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "certFile", ",", "keyFile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Panic", "(", "err", ")", "\n", "}", "\n", "config", ":=", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", ",", "ClientAuth", ":", "tls", ".", "RequireAnyClientCert", "}", "\n", "log", ".", "Print", "(", "\"", "\"", ")", "\n\n", "srv", ",", "_", ":=", "tls", ".", "Listen", "(", "\"", "\"", ",", "\"", "\"", ",", "&", "config", ")", "\n", "for", "{", "conn", ",", "err", ":=", "srv", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Panic", "(", "err", ")", "\n", "}", "\n", "go", "loop", "(", "conn", ")", "\n", "}", "\n", "}" ]
// StartMockFeedbackServer spins up a simple stand-in for the Apple // feedback service that can be used for testing purposes. Doesn't // handle many errors, etc. Just for the sake of having something "live" // to hit.
[ "StartMockFeedbackServer", "spins", "up", "a", "simple", "stand", "-", "in", "for", "the", "Apple", "feedback", "service", "that", "can", "be", "used", "for", "testing", "purposes", ".", "Doesn", "t", "handle", "many", "errors", "etc", ".", "Just", "for", "the", "sake", "of", "having", "something", "live", "to", "hit", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/mock_feedback_server.go#L16-L32
14,772
Coccodrillo/apns
push_notification.go
NewPushNotification
func NewPushNotification() (pn *PushNotification) { pn = new(PushNotification) pn.payload = make(map[string]interface{}) pn.Identifier = rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(IdentifierUbound) pn.Priority = 10 return }
go
func NewPushNotification() (pn *PushNotification) { pn = new(PushNotification) pn.payload = make(map[string]interface{}) pn.Identifier = rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(IdentifierUbound) pn.Priority = 10 return }
[ "func", "NewPushNotification", "(", ")", "(", "pn", "*", "PushNotification", ")", "{", "pn", "=", "new", "(", "PushNotification", ")", "\n", "pn", ".", "payload", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "pn", ".", "Identifier", "=", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ")", ".", "Int31n", "(", "IdentifierUbound", ")", "\n", "pn", ".", "Priority", "=", "10", "\n", "return", "\n", "}" ]
// NewPushNotification creates and returns a PushNotification structure. // It also initializes the pseudo-random identifier.
[ "NewPushNotification", "creates", "and", "returns", "a", "PushNotification", "structure", ".", "It", "also", "initializes", "the", "pseudo", "-", "random", "identifier", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/push_notification.go#L87-L93
14,773
Coccodrillo/apns
push_notification.go
AddPayload
func (pn *PushNotification) AddPayload(p *Payload) { // This deserves some explanation. // // Setting an exported field of type int to 0 // triggers the omitempty behavior if you've set it. // Since the badge is optional, we should omit it if // it's not set. However, we want to include it if the // value is 0, so there's a hack in push_notification.go // that exploits the fact that Apple treats -1 for a // badge value as though it were 0 (i.e. it clears the // badge but doesn't stop the notification from going // through successfully.) // // Still a hack though :) if p.Badge == 0 { p.Badge = -1 } pn.Set("aps", p) }
go
func (pn *PushNotification) AddPayload(p *Payload) { // This deserves some explanation. // // Setting an exported field of type int to 0 // triggers the omitempty behavior if you've set it. // Since the badge is optional, we should omit it if // it's not set. However, we want to include it if the // value is 0, so there's a hack in push_notification.go // that exploits the fact that Apple treats -1 for a // badge value as though it were 0 (i.e. it clears the // badge but doesn't stop the notification from going // through successfully.) // // Still a hack though :) if p.Badge == 0 { p.Badge = -1 } pn.Set("aps", p) }
[ "func", "(", "pn", "*", "PushNotification", ")", "AddPayload", "(", "p", "*", "Payload", ")", "{", "// This deserves some explanation.", "//", "// Setting an exported field of type int to 0", "// triggers the omitempty behavior if you've set it.", "// Since the badge is optional, we should omit it if", "// it's not set. However, we want to include it if the", "// value is 0, so there's a hack in push_notification.go", "// that exploits the fact that Apple treats -1 for a", "// badge value as though it were 0 (i.e. it clears the", "// badge but doesn't stop the notification from going", "// through successfully.)", "//", "// Still a hack though :)", "if", "p", ".", "Badge", "==", "0", "{", "p", ".", "Badge", "=", "-", "1", "\n", "}", "\n", "pn", ".", "Set", "(", "\"", "\"", ",", "p", ")", "\n", "}" ]
// AddPayload sets the "aps" payload section of the request. It also // has a hack described within to deal with specific zero values.
[ "AddPayload", "sets", "the", "aps", "payload", "section", "of", "the", "request", ".", "It", "also", "has", "a", "hack", "described", "within", "to", "deal", "with", "specific", "zero", "values", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/push_notification.go#L97-L115
14,774
Coccodrillo/apns
push_notification.go
Set
func (pn *PushNotification) Set(key string, value interface{}) { pn.payload[key] = value }
go
func (pn *PushNotification) Set(key string, value interface{}) { pn.payload[key] = value }
[ "func", "(", "pn", "*", "PushNotification", ")", "Set", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "pn", ".", "payload", "[", "key", "]", "=", "value", "\n", "}" ]
// Set defines the value of a payload key.
[ "Set", "defines", "the", "value", "of", "a", "payload", "key", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/push_notification.go#L123-L125
14,775
Coccodrillo/apns
push_notification.go
PayloadString
func (pn *PushNotification) PayloadString() (string, error) { j, err := pn.PayloadJSON() return string(j), err }
go
func (pn *PushNotification) PayloadString() (string, error) { j, err := pn.PayloadJSON() return string(j), err }
[ "func", "(", "pn", "*", "PushNotification", ")", "PayloadString", "(", ")", "(", "string", ",", "error", ")", "{", "j", ",", "err", ":=", "pn", ".", "PayloadJSON", "(", ")", "\n", "return", "string", "(", "j", ")", ",", "err", "\n", "}" ]
// PayloadString returns the current payload in string format.
[ "PayloadString", "returns", "the", "current", "payload", "in", "string", "format", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/push_notification.go#L133-L136
14,776
Coccodrillo/apns
push_notification.go
ToBytes
func (pn *PushNotification) ToBytes() ([]byte, error) { token, err := hex.DecodeString(pn.DeviceToken) if err != nil { return nil, err } if len(token) != deviceTokenLength { return nil, errors.New("device token has incorrect length") } payload, err := pn.PayloadJSON() if err != nil { return nil, err } if len(payload) > MaxPayloadSizeBytes { return nil, errors.New("payload is larger than the " + strconv.Itoa(MaxPayloadSizeBytes) + " byte limit") } frameBuffer := new(bytes.Buffer) binary.Write(frameBuffer, binary.BigEndian, uint8(deviceTokenItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(deviceTokenLength)) binary.Write(frameBuffer, binary.BigEndian, token) binary.Write(frameBuffer, binary.BigEndian, uint8(payloadItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(len(payload))) binary.Write(frameBuffer, binary.BigEndian, payload) binary.Write(frameBuffer, binary.BigEndian, uint8(notificationIdentifierItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(notificationIdentifierLength)) binary.Write(frameBuffer, binary.BigEndian, pn.Identifier) binary.Write(frameBuffer, binary.BigEndian, uint8(expirationDateItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(expirationDateLength)) binary.Write(frameBuffer, binary.BigEndian, pn.Expiry) binary.Write(frameBuffer, binary.BigEndian, uint8(priorityItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(priorityLength)) binary.Write(frameBuffer, binary.BigEndian, pn.Priority) buffer := bytes.NewBuffer([]byte{}) binary.Write(buffer, binary.BigEndian, uint8(pushCommandValue)) binary.Write(buffer, binary.BigEndian, uint32(frameBuffer.Len())) binary.Write(buffer, binary.BigEndian, frameBuffer.Bytes()) return buffer.Bytes(), nil }
go
func (pn *PushNotification) ToBytes() ([]byte, error) { token, err := hex.DecodeString(pn.DeviceToken) if err != nil { return nil, err } if len(token) != deviceTokenLength { return nil, errors.New("device token has incorrect length") } payload, err := pn.PayloadJSON() if err != nil { return nil, err } if len(payload) > MaxPayloadSizeBytes { return nil, errors.New("payload is larger than the " + strconv.Itoa(MaxPayloadSizeBytes) + " byte limit") } frameBuffer := new(bytes.Buffer) binary.Write(frameBuffer, binary.BigEndian, uint8(deviceTokenItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(deviceTokenLength)) binary.Write(frameBuffer, binary.BigEndian, token) binary.Write(frameBuffer, binary.BigEndian, uint8(payloadItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(len(payload))) binary.Write(frameBuffer, binary.BigEndian, payload) binary.Write(frameBuffer, binary.BigEndian, uint8(notificationIdentifierItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(notificationIdentifierLength)) binary.Write(frameBuffer, binary.BigEndian, pn.Identifier) binary.Write(frameBuffer, binary.BigEndian, uint8(expirationDateItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(expirationDateLength)) binary.Write(frameBuffer, binary.BigEndian, pn.Expiry) binary.Write(frameBuffer, binary.BigEndian, uint8(priorityItemid)) binary.Write(frameBuffer, binary.BigEndian, uint16(priorityLength)) binary.Write(frameBuffer, binary.BigEndian, pn.Priority) buffer := bytes.NewBuffer([]byte{}) binary.Write(buffer, binary.BigEndian, uint8(pushCommandValue)) binary.Write(buffer, binary.BigEndian, uint32(frameBuffer.Len())) binary.Write(buffer, binary.BigEndian, frameBuffer.Bytes()) return buffer.Bytes(), nil }
[ "func", "(", "pn", "*", "PushNotification", ")", "ToBytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "token", ",", "err", ":=", "hex", ".", "DecodeString", "(", "pn", ".", "DeviceToken", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "token", ")", "!=", "deviceTokenLength", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "payload", ",", "err", ":=", "pn", ".", "PayloadJSON", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "payload", ")", ">", "MaxPayloadSizeBytes", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "MaxPayloadSizeBytes", ")", "+", "\"", "\"", ")", "\n", "}", "\n\n", "frameBuffer", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint8", "(", "deviceTokenItemid", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint16", "(", "deviceTokenLength", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "token", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint8", "(", "payloadItemid", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint16", "(", "len", "(", "payload", ")", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "payload", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint8", "(", "notificationIdentifierItemid", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint16", "(", "notificationIdentifierLength", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "pn", ".", "Identifier", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint8", "(", "expirationDateItemid", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint16", "(", "expirationDateLength", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "pn", ".", "Expiry", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint8", "(", "priorityItemid", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "uint16", "(", "priorityLength", ")", ")", "\n", "binary", ".", "Write", "(", "frameBuffer", ",", "binary", ".", "BigEndian", ",", "pn", ".", "Priority", ")", "\n\n", "buffer", ":=", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "{", "}", ")", "\n", "binary", ".", "Write", "(", "buffer", ",", "binary", ".", "BigEndian", ",", "uint8", "(", "pushCommandValue", ")", ")", "\n", "binary", ".", "Write", "(", "buffer", ",", "binary", ".", "BigEndian", ",", "uint32", "(", "frameBuffer", ".", "Len", "(", ")", ")", ")", "\n", "binary", ".", "Write", "(", "buffer", ",", "binary", ".", "BigEndian", ",", "frameBuffer", ".", "Bytes", "(", ")", ")", "\n", "return", "buffer", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// ToBytes returns a byte array of the complete PushNotification // struct. This array is what should be transmitted to the APN Service.
[ "ToBytes", "returns", "a", "byte", "array", "of", "the", "complete", "PushNotification", "struct", ".", "This", "array", "is", "what", "should", "be", "transmitted", "to", "the", "APN", "Service", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/push_notification.go#L140-L178
14,777
Coccodrillo/apns
client.go
BareClient
func BareClient(gateway, certificateBase64, keyBase64 string) (c *Client) { c = new(Client) c.Gateway = gateway c.CertificateBase64 = certificateBase64 c.KeyBase64 = keyBase64 return }
go
func BareClient(gateway, certificateBase64, keyBase64 string) (c *Client) { c = new(Client) c.Gateway = gateway c.CertificateBase64 = certificateBase64 c.KeyBase64 = keyBase64 return }
[ "func", "BareClient", "(", "gateway", ",", "certificateBase64", ",", "keyBase64", "string", ")", "(", "c", "*", "Client", ")", "{", "c", "=", "new", "(", "Client", ")", "\n", "c", ".", "Gateway", "=", "gateway", "\n", "c", ".", "CertificateBase64", "=", "certificateBase64", "\n", "c", ".", "KeyBase64", "=", "keyBase64", "\n", "return", "\n", "}" ]
// BareClient can be used to set the contents of your // certificate and key blocks manually.
[ "BareClient", "can", "be", "used", "to", "set", "the", "contents", "of", "your", "certificate", "and", "key", "blocks", "manually", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/client.go#L39-L45
14,778
Coccodrillo/apns
client.go
NewClient
func NewClient(gateway, certificateFile, keyFile string) (c *Client) { c = new(Client) c.Gateway = gateway c.CertificateFile = certificateFile c.KeyFile = keyFile return }
go
func NewClient(gateway, certificateFile, keyFile string) (c *Client) { c = new(Client) c.Gateway = gateway c.CertificateFile = certificateFile c.KeyFile = keyFile return }
[ "func", "NewClient", "(", "gateway", ",", "certificateFile", ",", "keyFile", "string", ")", "(", "c", "*", "Client", ")", "{", "c", "=", "new", "(", "Client", ")", "\n", "c", ".", "Gateway", "=", "gateway", "\n", "c", ".", "CertificateFile", "=", "certificateFile", "\n", "c", ".", "KeyFile", "=", "keyFile", "\n", "return", "\n", "}" ]
// NewClient assumes you'll be passing in paths that // point to your certificate and key.
[ "NewClient", "assumes", "you", "ll", "be", "passing", "in", "paths", "that", "point", "to", "your", "certificate", "and", "key", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/client.go#L49-L55
14,779
Coccodrillo/apns
client.go
Send
func (client *Client) Send(pn *PushNotification) (resp *PushNotificationResponse) { resp = new(PushNotificationResponse) payload, err := pn.ToBytes() if err != nil { resp.Success = false resp.Error = err return } err = client.ConnectAndWrite(resp, payload) if err != nil { resp.Success = false resp.Error = err return } resp.Success = true resp.Error = nil return }
go
func (client *Client) Send(pn *PushNotification) (resp *PushNotificationResponse) { resp = new(PushNotificationResponse) payload, err := pn.ToBytes() if err != nil { resp.Success = false resp.Error = err return } err = client.ConnectAndWrite(resp, payload) if err != nil { resp.Success = false resp.Error = err return } resp.Success = true resp.Error = nil return }
[ "func", "(", "client", "*", "Client", ")", "Send", "(", "pn", "*", "PushNotification", ")", "(", "resp", "*", "PushNotificationResponse", ")", "{", "resp", "=", "new", "(", "PushNotificationResponse", ")", "\n\n", "payload", ",", "err", ":=", "pn", ".", "ToBytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "resp", ".", "Success", "=", "false", "\n", "resp", ".", "Error", "=", "err", "\n", "return", "\n", "}", "\n\n", "err", "=", "client", ".", "ConnectAndWrite", "(", "resp", ",", "payload", ")", "\n", "if", "err", "!=", "nil", "{", "resp", ".", "Success", "=", "false", "\n", "resp", ".", "Error", "=", "err", "\n", "return", "\n", "}", "\n\n", "resp", ".", "Success", "=", "true", "\n", "resp", ".", "Error", "=", "nil", "\n\n", "return", "\n", "}" ]
// Send connects to the APN service and sends your push notification. // Remember that if the submission is successful, Apple won't reply.
[ "Send", "connects", "to", "the", "APN", "service", "and", "sends", "your", "push", "notification", ".", "Remember", "that", "if", "the", "submission", "is", "successful", "Apple", "won", "t", "reply", "." ]
91763352f7bfc26cca140cda1dad70e0ec9a4236
https://github.com/Coccodrillo/apns/blob/91763352f7bfc26cca140cda1dad70e0ec9a4236/client.go#L59-L80
14,780
go4org/go4
types/types.go
ParseTime3339OrZero
func ParseTime3339OrZero(v string) Time3339 { t, err := time.Parse(time.RFC3339Nano, v) if err != nil { return Time3339{} } return Time3339(t) }
go
func ParseTime3339OrZero(v string) Time3339 { t, err := time.Parse(time.RFC3339Nano, v) if err != nil { return Time3339{} } return Time3339(t) }
[ "func", "ParseTime3339OrZero", "(", "v", "string", ")", "Time3339", "{", "t", ",", "err", ":=", "time", ".", "Parse", "(", "time", ".", "RFC3339Nano", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Time3339", "{", "}", "\n", "}", "\n", "return", "Time3339", "(", "t", ")", "\n", "}" ]
// ParseTime3339OrZero parses a string in RFC3339 format. If it's invalid, // the zero time value is returned instead.
[ "ParseTime3339OrZero", "parses", "a", "string", "in", "RFC3339", "format", ".", "If", "it", "s", "invalid", "the", "zero", "time", "value", "is", "returned", "instead", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/types/types.go#L87-L93
14,781
go4org/go4
types/types.go
IsAnyZero
func (t *Time3339) IsAnyZero() bool { return t == nil || time.Time(*t).IsZero() || time.Time(*t).Unix() == 0 }
go
func (t *Time3339) IsAnyZero() bool { return t == nil || time.Time(*t).IsZero() || time.Time(*t).Unix() == 0 }
[ "func", "(", "t", "*", "Time3339", ")", "IsAnyZero", "(", ")", "bool", "{", "return", "t", "==", "nil", "||", "time", ".", "Time", "(", "*", "t", ")", ".", "IsZero", "(", ")", "||", "time", ".", "Time", "(", "*", "t", ")", ".", "Unix", "(", ")", "==", "0", "\n", "}" ]
// IsAnyZero returns whether the time is Go zero or Unix zero.
[ "IsAnyZero", "returns", "whether", "the", "time", "is", "Go", "zero", "or", "Unix", "zero", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/types/types.go#L111-L113
14,782
go4org/go4
jsonconfig/eval.go
ReadFile
func (c *ConfigParser) ReadFile(path string) (Obj, error) { if path == "" && c.Open == nil { return nil, errors.New("ReadFile of empty string but Open hook not defined") } c.touchedFiles = make(map[string]bool) var err error c.rootJSON, err = c.recursiveReadJSON(path) return c.rootJSON, err }
go
func (c *ConfigParser) ReadFile(path string) (Obj, error) { if path == "" && c.Open == nil { return nil, errors.New("ReadFile of empty string but Open hook not defined") } c.touchedFiles = make(map[string]bool) var err error c.rootJSON, err = c.recursiveReadJSON(path) return c.rootJSON, err }
[ "func", "(", "c", "*", "ConfigParser", ")", "ReadFile", "(", "path", "string", ")", "(", "Obj", ",", "error", ")", "{", "if", "path", "==", "\"", "\"", "&&", "c", ".", "Open", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "touchedFiles", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "var", "err", "error", "\n", "c", ".", "rootJSON", ",", "err", "=", "c", ".", "recursiveReadJSON", "(", "path", ")", "\n", "return", "c", ".", "rootJSON", ",", "err", "\n", "}" ]
// ReadFile parses the provided path and returns the config file. // If path is empty, the c.Open function must be defined.
[ "ReadFile", "parses", "the", "provided", "path", "and", "returns", "the", "config", "file", ".", "If", "path", "is", "empty", "the", "c", ".", "Open", "function", "must", "be", "defined", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/jsonconfig/eval.go#L88-L96
14,783
go4org/go4
jsonconfig/eval.go
recursiveReadJSON
func (c *ConfigParser) recursiveReadJSON(configPath string) (decodedObject map[string]interface{}, err error) { if configPath != "" { absConfigPath, err := filepath.Abs(configPath) if err != nil { return nil, fmt.Errorf("Failed to expand absolute path for %s", configPath) } if c.touchedFiles[absConfigPath] { return nil, fmt.Errorf("ConfigParser include cycle detected reading config: %v", absConfigPath) } c.touchedFiles[absConfigPath] = true c.includeStack.Push(absConfigPath) defer c.includeStack.Pop() } var f File if f, err = c.open(configPath); err != nil { return nil, fmt.Errorf("Failed to open config: %v", err) } defer f.Close() decodedObject = make(map[string]interface{}) dj := json.NewDecoder(f) if err = dj.Decode(&decodedObject); err != nil { extra := "" if serr, ok := err.(*json.SyntaxError); ok { if _, serr := f.Seek(0, os.SEEK_SET); serr != nil { log.Fatalf("seek error: %v", serr) } line, col, highlight := errorutil.HighlightBytePosition(f, serr.Offset) extra = fmt.Sprintf(":\nError at line %d, column %d (file offset %d):\n%s", line, col, serr.Offset, highlight) } return nil, fmt.Errorf("error parsing JSON object in config file %s%s\n%v", f.Name(), extra, err) } if err = c.evaluateExpressions(decodedObject, nil, false); err != nil { return nil, fmt.Errorf("error expanding JSON config expressions in %s:\n%v", f.Name(), err) } return decodedObject, nil }
go
func (c *ConfigParser) recursiveReadJSON(configPath string) (decodedObject map[string]interface{}, err error) { if configPath != "" { absConfigPath, err := filepath.Abs(configPath) if err != nil { return nil, fmt.Errorf("Failed to expand absolute path for %s", configPath) } if c.touchedFiles[absConfigPath] { return nil, fmt.Errorf("ConfigParser include cycle detected reading config: %v", absConfigPath) } c.touchedFiles[absConfigPath] = true c.includeStack.Push(absConfigPath) defer c.includeStack.Pop() } var f File if f, err = c.open(configPath); err != nil { return nil, fmt.Errorf("Failed to open config: %v", err) } defer f.Close() decodedObject = make(map[string]interface{}) dj := json.NewDecoder(f) if err = dj.Decode(&decodedObject); err != nil { extra := "" if serr, ok := err.(*json.SyntaxError); ok { if _, serr := f.Seek(0, os.SEEK_SET); serr != nil { log.Fatalf("seek error: %v", serr) } line, col, highlight := errorutil.HighlightBytePosition(f, serr.Offset) extra = fmt.Sprintf(":\nError at line %d, column %d (file offset %d):\n%s", line, col, serr.Offset, highlight) } return nil, fmt.Errorf("error parsing JSON object in config file %s%s\n%v", f.Name(), extra, err) } if err = c.evaluateExpressions(decodedObject, nil, false); err != nil { return nil, fmt.Errorf("error expanding JSON config expressions in %s:\n%v", f.Name(), err) } return decodedObject, nil }
[ "func", "(", "c", "*", "ConfigParser", ")", "recursiveReadJSON", "(", "configPath", "string", ")", "(", "decodedObject", "map", "[", "string", "]", "interface", "{", "}", ",", "err", "error", ")", "{", "if", "configPath", "!=", "\"", "\"", "{", "absConfigPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "configPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "configPath", ")", "\n", "}", "\n", "if", "c", ".", "touchedFiles", "[", "absConfigPath", "]", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "absConfigPath", ")", "\n", "}", "\n", "c", ".", "touchedFiles", "[", "absConfigPath", "]", "=", "true", "\n\n", "c", ".", "includeStack", ".", "Push", "(", "absConfigPath", ")", "\n", "defer", "c", ".", "includeStack", ".", "Pop", "(", ")", "\n", "}", "\n\n", "var", "f", "File", "\n", "if", "f", ",", "err", "=", "c", ".", "open", "(", "configPath", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "decodedObject", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "dj", ":=", "json", ".", "NewDecoder", "(", "f", ")", "\n", "if", "err", "=", "dj", ".", "Decode", "(", "&", "decodedObject", ")", ";", "err", "!=", "nil", "{", "extra", ":=", "\"", "\"", "\n", "if", "serr", ",", "ok", ":=", "err", ".", "(", "*", "json", ".", "SyntaxError", ")", ";", "ok", "{", "if", "_", ",", "serr", ":=", "f", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", ";", "serr", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "serr", ")", "\n", "}", "\n", "line", ",", "col", ",", "highlight", ":=", "errorutil", ".", "HighlightBytePosition", "(", "f", ",", "serr", ".", "Offset", ")", "\n", "extra", "=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "line", ",", "col", ",", "serr", ".", "Offset", ",", "highlight", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "f", ".", "Name", "(", ")", ",", "extra", ",", "err", ")", "\n", "}", "\n\n", "if", "err", "=", "c", ".", "evaluateExpressions", "(", "decodedObject", ",", "nil", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "decodedObject", ",", "nil", "\n", "}" ]
// Decodes and evaluates a json config file, watching for include cycles.
[ "Decodes", "and", "evaluates", "a", "json", "config", "file", "watching", "for", "include", "cycles", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/jsonconfig/eval.go#L99-L143
14,784
go4org/go4
jsonconfig/eval.go
CheckTypes
func (c *ConfigParser) CheckTypes(m map[string]interface{}) error { return c.evaluateExpressions(m, nil, true) }
go
func (c *ConfigParser) CheckTypes(m map[string]interface{}) error { return c.evaluateExpressions(m, nil, true) }
[ "func", "(", "c", "*", "ConfigParser", ")", "CheckTypes", "(", "m", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "evaluateExpressions", "(", "m", ",", "nil", ",", "true", ")", "\n", "}" ]
// CheckTypes parses m and returns an error if it encounters a type or value // that is not supported by this package.
[ "CheckTypes", "parses", "m", "and", "returns", "an", "error", "if", "it", "encounters", "a", "type", "or", "value", "that", "is", "not", "supported", "by", "this", "package", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/jsonconfig/eval.go#L199-L201
14,785
go4org/go4
jsonconfig/eval.go
evaluateExpressions
func (c *ConfigParser) evaluateExpressions(m map[string]interface{}, seenKeys []string, testOnly bool) error { for k, ei := range m { thisPath := append(seenKeys, k) switch subval := ei.(type) { case string, bool, float64, nil: continue case []interface{}: if len(subval) == 0 { continue } evaled, err := c.evalValue(subval) if err != nil { return fmt.Errorf("%s: value error %v", strings.Join(thisPath, "."), err) } if !testOnly { m[k] = evaled } case map[string]interface{}: if err := c.evaluateExpressions(subval, thisPath, testOnly); err != nil { return err } default: return fmt.Errorf("%s: unhandled type %T", strings.Join(thisPath, "."), ei) } } return nil }
go
func (c *ConfigParser) evaluateExpressions(m map[string]interface{}, seenKeys []string, testOnly bool) error { for k, ei := range m { thisPath := append(seenKeys, k) switch subval := ei.(type) { case string, bool, float64, nil: continue case []interface{}: if len(subval) == 0 { continue } evaled, err := c.evalValue(subval) if err != nil { return fmt.Errorf("%s: value error %v", strings.Join(thisPath, "."), err) } if !testOnly { m[k] = evaled } case map[string]interface{}: if err := c.evaluateExpressions(subval, thisPath, testOnly); err != nil { return err } default: return fmt.Errorf("%s: unhandled type %T", strings.Join(thisPath, "."), ei) } } return nil }
[ "func", "(", "c", "*", "ConfigParser", ")", "evaluateExpressions", "(", "m", "map", "[", "string", "]", "interface", "{", "}", ",", "seenKeys", "[", "]", "string", ",", "testOnly", "bool", ")", "error", "{", "for", "k", ",", "ei", ":=", "range", "m", "{", "thisPath", ":=", "append", "(", "seenKeys", ",", "k", ")", "\n", "switch", "subval", ":=", "ei", ".", "(", "type", ")", "{", "case", "string", ",", "bool", ",", "float64", ",", "nil", ":", "continue", "\n", "case", "[", "]", "interface", "{", "}", ":", "if", "len", "(", "subval", ")", "==", "0", "{", "continue", "\n", "}", "\n", "evaled", ",", "err", ":=", "c", ".", "evalValue", "(", "subval", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "thisPath", ",", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "!", "testOnly", "{", "m", "[", "k", "]", "=", "evaled", "\n", "}", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "if", "err", ":=", "c", ".", "evaluateExpressions", "(", "subval", ",", "thisPath", ",", "testOnly", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "thisPath", ",", "\"", "\"", ")", ",", "ei", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// evaluateExpressions parses recursively m, populating it with the values // that are found, unless testOnly is true.
[ "evaluateExpressions", "parses", "recursively", "m", "populating", "it", "with", "the", "values", "that", "are", "found", "unless", "testOnly", "is", "true", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/jsonconfig/eval.go#L205-L231
14,786
go4org/go4
jsonconfig/eval.go
ConfigFilePath
func (c *ConfigParser) ConfigFilePath(configFile string) (path string, err error) { // Try to open as absolute / relative to CWD _, err = os.Stat(configFile) if err != nil && filepath.IsAbs(configFile) { return "", err } if err == nil { return configFile, nil } for _, d := range c.IncludeDirs { if _, err := os.Stat(filepath.Join(d, configFile)); err == nil { return filepath.Join(d, configFile), nil } } return "", os.ErrNotExist }
go
func (c *ConfigParser) ConfigFilePath(configFile string) (path string, err error) { // Try to open as absolute / relative to CWD _, err = os.Stat(configFile) if err != nil && filepath.IsAbs(configFile) { return "", err } if err == nil { return configFile, nil } for _, d := range c.IncludeDirs { if _, err := os.Stat(filepath.Join(d, configFile)); err == nil { return filepath.Join(d, configFile), nil } } return "", os.ErrNotExist }
[ "func", "(", "c", "*", "ConfigParser", ")", "ConfigFilePath", "(", "configFile", "string", ")", "(", "path", "string", ",", "err", "error", ")", "{", "// Try to open as absolute / relative to CWD", "_", ",", "err", "=", "os", ".", "Stat", "(", "configFile", ")", "\n", "if", "err", "!=", "nil", "&&", "filepath", ".", "IsAbs", "(", "configFile", ")", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "err", "==", "nil", "{", "return", "configFile", ",", "nil", "\n", "}", "\n\n", "for", "_", ",", "d", ":=", "range", "c", ".", "IncludeDirs", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "d", ",", "configFile", ")", ")", ";", "err", "==", "nil", "{", "return", "filepath", ".", "Join", "(", "d", ",", "configFile", ")", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", ",", "os", ".", "ErrNotExist", "\n", "}" ]
// ConfigFilePath checks if configFile is found and returns a usable path to it. // It first checks if configFile is an absolute path, or if it's found in the // current working directory. If not, it then checks if configFile is in one of // c.IncludeDirs. It returns an error if configFile is absolute and could not be // statted, or os.ErrNotExist if configFile was not found.
[ "ConfigFilePath", "checks", "if", "configFile", "is", "found", "and", "returns", "a", "usable", "path", "to", "it", ".", "It", "first", "checks", "if", "configFile", "is", "an", "absolute", "path", "or", "if", "it", "s", "found", "in", "the", "current", "working", "directory", ".", "If", "not", "it", "then", "checks", "if", "configFile", "is", "in", "one", "of", "c", ".", "IncludeDirs", ".", "It", "returns", "an", "error", "if", "configFile", "is", "absolute", "and", "could", "not", "be", "statted", "or", "os", ".", "ErrNotExist", "if", "configFile", "was", "not", "found", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/jsonconfig/eval.go#L304-L321
14,787
go4org/go4
oauthutil/oauth.go
cachedToken
func cachedToken(cacheFile string) (*oauth2.Token, error) { tok := new(oauth2.Token) tokenData, err := wkfs.ReadFile(cacheFile) if err != nil { return nil, err } if err = json.Unmarshal(tokenData, tok); err != nil { return nil, err } if !tok.Valid() { if tok != nil && time.Now().After(tok.Expiry) { return nil, errExpiredToken } return nil, errors.New("invalid token") } return tok, nil }
go
func cachedToken(cacheFile string) (*oauth2.Token, error) { tok := new(oauth2.Token) tokenData, err := wkfs.ReadFile(cacheFile) if err != nil { return nil, err } if err = json.Unmarshal(tokenData, tok); err != nil { return nil, err } if !tok.Valid() { if tok != nil && time.Now().After(tok.Expiry) { return nil, errExpiredToken } return nil, errors.New("invalid token") } return tok, nil }
[ "func", "cachedToken", "(", "cacheFile", "string", ")", "(", "*", "oauth2", ".", "Token", ",", "error", ")", "{", "tok", ":=", "new", "(", "oauth2", ".", "Token", ")", "\n", "tokenData", ",", "err", ":=", "wkfs", ".", "ReadFile", "(", "cacheFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "tokenData", ",", "tok", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "tok", ".", "Valid", "(", ")", "{", "if", "tok", "!=", "nil", "&&", "time", ".", "Now", "(", ")", ".", "After", "(", "tok", ".", "Expiry", ")", "{", "return", "nil", ",", "errExpiredToken", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "tok", ",", "nil", "\n", "}" ]
// cachedToken returns the token saved in cacheFile. It specifically returns // errTokenExpired if the token is expired.
[ "cachedToken", "returns", "the", "token", "saved", "in", "cacheFile", ".", "It", "specifically", "returns", "errTokenExpired", "if", "the", "token", "is", "expired", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/oauthutil/oauth.go#L59-L75
14,788
go4org/go4
oauthutil/oauth.go
NewRefreshTokenSource
func NewRefreshTokenSource(config *oauth2.Config, refreshToken string) oauth2.TokenSource { var noInitialToken *oauth2.Token = nil return oauth2.ReuseTokenSource(noInitialToken, config.TokenSource( oauth2.NoContext, // TODO: maybe accept a context later. &oauth2.Token{RefreshToken: refreshToken}, )) }
go
func NewRefreshTokenSource(config *oauth2.Config, refreshToken string) oauth2.TokenSource { var noInitialToken *oauth2.Token = nil return oauth2.ReuseTokenSource(noInitialToken, config.TokenSource( oauth2.NoContext, // TODO: maybe accept a context later. &oauth2.Token{RefreshToken: refreshToken}, )) }
[ "func", "NewRefreshTokenSource", "(", "config", "*", "oauth2", ".", "Config", ",", "refreshToken", "string", ")", "oauth2", ".", "TokenSource", "{", "var", "noInitialToken", "*", "oauth2", ".", "Token", "=", "nil", "\n", "return", "oauth2", ".", "ReuseTokenSource", "(", "noInitialToken", ",", "config", ".", "TokenSource", "(", "oauth2", ".", "NoContext", ",", "// TODO: maybe accept a context later.", "&", "oauth2", ".", "Token", "{", "RefreshToken", ":", "refreshToken", "}", ",", ")", ")", "\n", "}" ]
// NewRefreshTokenSource returns a token source that obtains its initial token // based on the provided config and the refresh token.
[ "NewRefreshTokenSource", "returns", "a", "token", "source", "that", "obtains", "its", "initial", "token", "based", "on", "the", "provided", "config", "and", "the", "refresh", "token", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/oauthutil/oauth.go#L115-L121
14,789
go4org/go4
media/heif/bmff/bmff.go
ReadBox
func (r *Reader) ReadBox() (Box, error) { if r.noMoreBoxes { return nil, io.EOF } if r.lastBox != nil { if _, err := io.Copy(ioutil.Discard, r.lastBox.Body()); err != nil { return nil, err } } var buf [8]byte _, err := io.ReadFull(r.br, buf[:4]) if err != nil { return nil, err } box := &box{ size: int64(binary.BigEndian.Uint32(buf[:4])), } _, err = io.ReadFull(r.br, box.boxType[:]) // 4 more bytes if err != nil { return nil, err } // Special cases for size: var remain int64 switch box.size { case 1: // 1 means it's actually a 64-bit size, after the type. _, err = io.ReadFull(r.br, buf[:8]) if err != nil { return nil, err } box.size = int64(binary.BigEndian.Uint64(buf[:8])) if box.size < 0 { // Go uses int64 for sizes typically, but BMFF uses uint64. // We assume for now that nobody actually uses boxes larger // than int64. return nil, fmt.Errorf("unexpectedly large box %q", box.boxType) } remain = box.size - 2*4 - 8 case 0: // 0 means unknown & to read to end of file. No more boxes. r.noMoreBoxes = true default: remain = box.size - 2*4 } if remain < 0 { return nil, fmt.Errorf("Box header for %q has size %d, suggesting %d (negative) bytes remain", box.boxType, box.size, remain) } if box.size > 0 { box.body = io.LimitReader(r.br, remain) } else { box.body = r.br } r.lastBox = box return box, nil }
go
func (r *Reader) ReadBox() (Box, error) { if r.noMoreBoxes { return nil, io.EOF } if r.lastBox != nil { if _, err := io.Copy(ioutil.Discard, r.lastBox.Body()); err != nil { return nil, err } } var buf [8]byte _, err := io.ReadFull(r.br, buf[:4]) if err != nil { return nil, err } box := &box{ size: int64(binary.BigEndian.Uint32(buf[:4])), } _, err = io.ReadFull(r.br, box.boxType[:]) // 4 more bytes if err != nil { return nil, err } // Special cases for size: var remain int64 switch box.size { case 1: // 1 means it's actually a 64-bit size, after the type. _, err = io.ReadFull(r.br, buf[:8]) if err != nil { return nil, err } box.size = int64(binary.BigEndian.Uint64(buf[:8])) if box.size < 0 { // Go uses int64 for sizes typically, but BMFF uses uint64. // We assume for now that nobody actually uses boxes larger // than int64. return nil, fmt.Errorf("unexpectedly large box %q", box.boxType) } remain = box.size - 2*4 - 8 case 0: // 0 means unknown & to read to end of file. No more boxes. r.noMoreBoxes = true default: remain = box.size - 2*4 } if remain < 0 { return nil, fmt.Errorf("Box header for %q has size %d, suggesting %d (negative) bytes remain", box.boxType, box.size, remain) } if box.size > 0 { box.body = io.LimitReader(r.br, remain) } else { box.body = r.br } r.lastBox = box return box, nil }
[ "func", "(", "r", "*", "Reader", ")", "ReadBox", "(", ")", "(", "Box", ",", "error", ")", "{", "if", "r", ".", "noMoreBoxes", "{", "return", "nil", ",", "io", ".", "EOF", "\n", "}", "\n", "if", "r", ".", "lastBox", "!=", "nil", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "r", ".", "lastBox", ".", "Body", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "var", "buf", "[", "8", "]", "byte", "\n\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ".", "br", ",", "buf", "[", ":", "4", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "box", ":=", "&", "box", "{", "size", ":", "int64", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "buf", "[", ":", "4", "]", ")", ")", ",", "}", "\n\n", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ".", "br", ",", "box", ".", "boxType", "[", ":", "]", ")", "// 4 more bytes", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Special cases for size:", "var", "remain", "int64", "\n", "switch", "box", ".", "size", "{", "case", "1", ":", "// 1 means it's actually a 64-bit size, after the type.", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ".", "br", ",", "buf", "[", ":", "8", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "box", ".", "size", "=", "int64", "(", "binary", ".", "BigEndian", ".", "Uint64", "(", "buf", "[", ":", "8", "]", ")", ")", "\n", "if", "box", ".", "size", "<", "0", "{", "// Go uses int64 for sizes typically, but BMFF uses uint64.", "// We assume for now that nobody actually uses boxes larger", "// than int64.", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "box", ".", "boxType", ")", "\n", "}", "\n", "remain", "=", "box", ".", "size", "-", "2", "*", "4", "-", "8", "\n", "case", "0", ":", "// 0 means unknown & to read to end of file. No more boxes.", "r", ".", "noMoreBoxes", "=", "true", "\n", "default", ":", "remain", "=", "box", ".", "size", "-", "2", "*", "4", "\n", "}", "\n", "if", "remain", "<", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "box", ".", "boxType", ",", "box", ".", "size", ",", "remain", ")", "\n", "}", "\n", "if", "box", ".", "size", ">", "0", "{", "box", ".", "body", "=", "io", ".", "LimitReader", "(", "r", ".", "br", ",", "remain", ")", "\n", "}", "else", "{", "box", ".", "body", "=", "r", ".", "br", "\n", "}", "\n", "r", ".", "lastBox", "=", "box", "\n", "return", "box", ",", "nil", "\n", "}" ]
// ReadBox reads the next box. // // If the previously read box was not read to completion, ReadBox consumes // the rest of its data. // // At the end, the error is io.EOF.
[ "ReadBox", "reads", "the", "next", "box", ".", "If", "the", "previously", "read", "box", "was", "not", "read", "to", "completion", "ReadBox", "consumes", "the", "rest", "of", "its", "data", ".", "At", "the", "end", "the", "error", "is", "io", ".", "EOF", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/media/heif/bmff/bmff.go#L167-L224
14,790
go4org/go4
media/heif/bmff/bmff.go
ReadAndParseBox
func (r *Reader) ReadAndParseBox(typ BoxType) (Box, error) { box, err := r.ReadBox() if err != nil { return nil, fmt.Errorf("error reading %q box: %v", typ, err) } if box.Type() != typ { return nil, fmt.Errorf("error reading %q box: got box type %q instead", typ, box.Type()) } pbox, err := box.Parse() if err != nil { return nil, fmt.Errorf("error parsing read %q box: %v", typ, err) } return pbox, nil }
go
func (r *Reader) ReadAndParseBox(typ BoxType) (Box, error) { box, err := r.ReadBox() if err != nil { return nil, fmt.Errorf("error reading %q box: %v", typ, err) } if box.Type() != typ { return nil, fmt.Errorf("error reading %q box: got box type %q instead", typ, box.Type()) } pbox, err := box.Parse() if err != nil { return nil, fmt.Errorf("error parsing read %q box: %v", typ, err) } return pbox, nil }
[ "func", "(", "r", "*", "Reader", ")", "ReadAndParseBox", "(", "typ", "BoxType", ")", "(", "Box", ",", "error", ")", "{", "box", ",", "err", ":=", "r", ".", "ReadBox", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typ", ",", "err", ")", "\n", "}", "\n", "if", "box", ".", "Type", "(", ")", "!=", "typ", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typ", ",", "box", ".", "Type", "(", ")", ")", "\n", "}", "\n", "pbox", ",", "err", ":=", "box", ".", "Parse", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typ", ",", "err", ")", "\n", "}", "\n", "return", "pbox", ",", "nil", "\n", "}" ]
// ReadAndParseBox wraps the ReadBox method, ensuring that the read box is of type typ // and parses successfully. It returns the parsed box.
[ "ReadAndParseBox", "wraps", "the", "ReadBox", "method", "ensuring", "that", "the", "read", "box", "is", "of", "type", "typ", "and", "parses", "successfully", ".", "It", "returns", "the", "parsed", "box", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/media/heif/bmff/bmff.go#L228-L241
14,791
go4org/go4
net/throttle/throttle.go
byteTime
func (r Rate) byteTime(n int) time.Duration { if r.KBps == 0 { return 0 } return time.Duration(float64(n)/1024/float64(r.KBps)) * time.Second }
go
func (r Rate) byteTime(n int) time.Duration { if r.KBps == 0 { return 0 } return time.Duration(float64(n)/1024/float64(r.KBps)) * time.Second }
[ "func", "(", "r", "Rate", ")", "byteTime", "(", "n", "int", ")", "time", ".", "Duration", "{", "if", "r", ".", "KBps", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "time", ".", "Duration", "(", "float64", "(", "n", ")", "/", "1024", "/", "float64", "(", "r", ".", "KBps", ")", ")", "*", "time", ".", "Second", "\n", "}" ]
// byteTime returns the time required for n bytes.
[ "byteTime", "returns", "the", "time", "required", "for", "n", "bytes", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/net/throttle/throttle.go#L37-L42
14,792
go4org/go4
lock/lock.go
lockPortable
func lockPortable(name string) (io.Closer, error) { fi, err := os.Stat(name) if err == nil && fi.Size() > 0 { st := portableLockStatus(name) switch st { case statusLocked: return nil, fmt.Errorf("file %q already locked", name) case statusStale: os.Remove(name) case statusInvalid: return nil, fmt.Errorf("can't Lock file %q: has invalid contents", name) } } f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_EXCL, 0666) if err != nil { return nil, fmt.Errorf("failed to create lock file %s %v", name, err) } if err := json.NewEncoder(f).Encode(&pidLockMeta{OwnerPID: os.Getpid()}); err != nil { return nil, fmt.Errorf("cannot write owner pid: %v", err) } return &unlocker{ f: f, abs: name, portable: true, }, nil }
go
func lockPortable(name string) (io.Closer, error) { fi, err := os.Stat(name) if err == nil && fi.Size() > 0 { st := portableLockStatus(name) switch st { case statusLocked: return nil, fmt.Errorf("file %q already locked", name) case statusStale: os.Remove(name) case statusInvalid: return nil, fmt.Errorf("can't Lock file %q: has invalid contents", name) } } f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_EXCL, 0666) if err != nil { return nil, fmt.Errorf("failed to create lock file %s %v", name, err) } if err := json.NewEncoder(f).Encode(&pidLockMeta{OwnerPID: os.Getpid()}); err != nil { return nil, fmt.Errorf("cannot write owner pid: %v", err) } return &unlocker{ f: f, abs: name, portable: true, }, nil }
[ "func", "lockPortable", "(", "name", "string", ")", "(", "io", ".", "Closer", ",", "error", ")", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "name", ")", "\n", "if", "err", "==", "nil", "&&", "fi", ".", "Size", "(", ")", ">", "0", "{", "st", ":=", "portableLockStatus", "(", "name", ")", "\n", "switch", "st", "{", "case", "statusLocked", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "case", "statusStale", ":", "os", ".", "Remove", "(", "name", ")", "\n", "case", "statusInvalid", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "}", "\n", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "name", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", "|", "os", ".", "O_EXCL", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "f", ")", ".", "Encode", "(", "&", "pidLockMeta", "{", "OwnerPID", ":", "os", ".", "Getpid", "(", ")", "}", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "&", "unlocker", "{", "f", ":", "f", ",", "abs", ":", "name", ",", "portable", ":", "true", ",", "}", ",", "nil", "\n", "}" ]
// lockPortable is a portable version not using fcntl. Doesn't handle crashes as gracefully, // since it can leave stale lock files.
[ "lockPortable", "is", "a", "portable", "version", "not", "using", "fcntl", ".", "Doesn", "t", "handle", "crashes", "as", "gracefully", "since", "it", "can", "leave", "stale", "lock", "files", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/lock/lock.go#L70-L95
14,793
go4org/go4
cloud/google/gcsutil/storage.go
simpleRequest
func simpleRequest(method, url_ string) (*http.Request, error) { req, err := http.NewRequest(method, url_, nil) if err != nil { return nil, err } req.Header.Set("x-goog-api-version", "2") return req, err }
go
func simpleRequest(method, url_ string) (*http.Request, error) { req, err := http.NewRequest(method, url_, nil) if err != nil { return nil, err } req.Header.Set("x-goog-api-version", "2") return req, err }
[ "func", "simpleRequest", "(", "method", ",", "url_", "string", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "url_", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "req", ",", "err", "\n", "}" ]
// Makes a simple body-less google storage request
[ "Makes", "a", "simple", "body", "-", "less", "google", "storage", "request" ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/cloud/google/gcsutil/storage.go#L76-L83
14,794
go4org/go4
cloud/google/gcsutil/storage.go
GetPartialObject
func GetPartialObject(ctx context.Context, obj Object, offset, length int64) (io.ReadCloser, error) { if offset < 0 { return nil, errors.New("invalid negative offset") } if err := obj.valid(); err != nil { return nil, err } req, err := simpleRequest("GET", gsAccessURL+"/"+obj.Bucket+"/"+obj.Key) if err != nil { return nil, err } if length >= 0 { req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) } else { req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) } req.Cancel = ctx.Done() res, err := ctxutil.Client(ctx).Do(req) if err != nil { return nil, fmt.Errorf("GET (offset=%d, length=%d) failed: %v\n", offset, length, err) } if res.StatusCode == http.StatusNotFound { res.Body.Close() return nil, os.ErrNotExist } if !(res.StatusCode == http.StatusPartialContent || (offset == 0 && res.StatusCode == http.StatusOK)) { res.Body.Close() if res.StatusCode == http.StatusRequestedRangeNotSatisfiable { return nil, ErrInvalidRange } return nil, fmt.Errorf("GET (offset=%d, length=%d) got failed status: %v\n", offset, length, res.Status) } return res.Body, nil }
go
func GetPartialObject(ctx context.Context, obj Object, offset, length int64) (io.ReadCloser, error) { if offset < 0 { return nil, errors.New("invalid negative offset") } if err := obj.valid(); err != nil { return nil, err } req, err := simpleRequest("GET", gsAccessURL+"/"+obj.Bucket+"/"+obj.Key) if err != nil { return nil, err } if length >= 0 { req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) } else { req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) } req.Cancel = ctx.Done() res, err := ctxutil.Client(ctx).Do(req) if err != nil { return nil, fmt.Errorf("GET (offset=%d, length=%d) failed: %v\n", offset, length, err) } if res.StatusCode == http.StatusNotFound { res.Body.Close() return nil, os.ErrNotExist } if !(res.StatusCode == http.StatusPartialContent || (offset == 0 && res.StatusCode == http.StatusOK)) { res.Body.Close() if res.StatusCode == http.StatusRequestedRangeNotSatisfiable { return nil, ErrInvalidRange } return nil, fmt.Errorf("GET (offset=%d, length=%d) got failed status: %v\n", offset, length, res.Status) } return res.Body, nil }
[ "func", "GetPartialObject", "(", "ctx", "context", ".", "Context", ",", "obj", "Object", ",", "offset", ",", "length", "int64", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "if", "offset", "<", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "obj", ".", "valid", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "req", ",", "err", ":=", "simpleRequest", "(", "\"", "\"", ",", "gsAccessURL", "+", "\"", "\"", "+", "obj", ".", "Bucket", "+", "\"", "\"", "+", "obj", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "length", ">=", "0", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "offset", ",", "offset", "+", "length", "-", "1", ")", ")", "\n", "}", "else", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "offset", ")", ")", "\n", "}", "\n", "req", ".", "Cancel", "=", "ctx", ".", "Done", "(", ")", "\n", "res", ",", "err", ":=", "ctxutil", ".", "Client", "(", "ctx", ")", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "offset", ",", "length", ",", "err", ")", "\n", "}", "\n", "if", "res", ".", "StatusCode", "==", "http", ".", "StatusNotFound", "{", "res", ".", "Body", ".", "Close", "(", ")", "\n", "return", "nil", ",", "os", ".", "ErrNotExist", "\n", "}", "\n", "if", "!", "(", "res", ".", "StatusCode", "==", "http", ".", "StatusPartialContent", "||", "(", "offset", "==", "0", "&&", "res", ".", "StatusCode", "==", "http", ".", "StatusOK", ")", ")", "{", "res", ".", "Body", ".", "Close", "(", ")", "\n", "if", "res", ".", "StatusCode", "==", "http", ".", "StatusRequestedRangeNotSatisfiable", "{", "return", "nil", ",", "ErrInvalidRange", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "offset", ",", "length", ",", "res", ".", "Status", ")", "\n", "}", "\n\n", "return", "res", ".", "Body", ",", "nil", "\n", "}" ]
// GetPartialObject fetches part of a Google Cloud Storage object. // This function relies on the ctx ctxutil.HTTPClient value being set to an OAuth2 // authorized and authenticated HTTP client. // If length is negative, the rest of the object is returned. // It returns ErrInvalidRange if the server replies with http.StatusRequestedRangeNotSatisfiable. // The caller must call Close on the returned value.
[ "GetPartialObject", "fetches", "part", "of", "a", "Google", "Cloud", "Storage", "object", ".", "This", "function", "relies", "on", "the", "ctx", "ctxutil", ".", "HTTPClient", "value", "being", "set", "to", "an", "OAuth2", "authorized", "and", "authenticated", "HTTP", "client", ".", "If", "length", "is", "negative", "the", "rest", "of", "the", "object", "is", "returned", ".", "It", "returns", "ErrInvalidRange", "if", "the", "server", "replies", "with", "http", ".", "StatusRequestedRangeNotSatisfiable", ".", "The", "caller", "must", "call", "Close", "on", "the", "returned", "value", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/cloud/google/gcsutil/storage.go#L94-L129
14,795
go4org/go4
cloud/google/gcsutil/storage.go
EnumerateObjects
func EnumerateObjects(ctx context.Context, bucket, after string, limit int) ([]*storage.ObjectAttrs, error) { // Build url, with query params var params []string if after != "" { params = append(params, "marker="+url.QueryEscape(after)) } if limit > 0 { params = append(params, fmt.Sprintf("max-keys=%v", limit)) } query := "" if len(params) > 0 { query = "?" + strings.Join(params, "&") } req, err := simpleRequest("GET", gsAccessURL+"/"+bucket+"/"+query) if err != nil { return nil, err } req.Cancel = ctx.Done() res, err := ctxutil.Client(ctx).Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("gcsutil: bad enumerate response code: %v", res.Status) } var xres struct { Contents []SizedObject } if err = xml.NewDecoder(res.Body).Decode(&xres); err != nil { return nil, err } objAttrs := make([]*storage.ObjectAttrs, len(xres.Contents)) for k, o := range xres.Contents { objAttrs[k] = &storage.ObjectAttrs{ Name: o.Key, Size: o.Size, } } return objAttrs, nil }
go
func EnumerateObjects(ctx context.Context, bucket, after string, limit int) ([]*storage.ObjectAttrs, error) { // Build url, with query params var params []string if after != "" { params = append(params, "marker="+url.QueryEscape(after)) } if limit > 0 { params = append(params, fmt.Sprintf("max-keys=%v", limit)) } query := "" if len(params) > 0 { query = "?" + strings.Join(params, "&") } req, err := simpleRequest("GET", gsAccessURL+"/"+bucket+"/"+query) if err != nil { return nil, err } req.Cancel = ctx.Done() res, err := ctxutil.Client(ctx).Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("gcsutil: bad enumerate response code: %v", res.Status) } var xres struct { Contents []SizedObject } if err = xml.NewDecoder(res.Body).Decode(&xres); err != nil { return nil, err } objAttrs := make([]*storage.ObjectAttrs, len(xres.Contents)) for k, o := range xres.Contents { objAttrs[k] = &storage.ObjectAttrs{ Name: o.Key, Size: o.Size, } } return objAttrs, nil }
[ "func", "EnumerateObjects", "(", "ctx", "context", ".", "Context", ",", "bucket", ",", "after", "string", ",", "limit", "int", ")", "(", "[", "]", "*", "storage", ".", "ObjectAttrs", ",", "error", ")", "{", "// Build url, with query params", "var", "params", "[", "]", "string", "\n", "if", "after", "!=", "\"", "\"", "{", "params", "=", "append", "(", "params", ",", "\"", "\"", "+", "url", ".", "QueryEscape", "(", "after", ")", ")", "\n", "}", "\n", "if", "limit", ">", "0", "{", "params", "=", "append", "(", "params", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "limit", ")", ")", "\n", "}", "\n", "query", ":=", "\"", "\"", "\n", "if", "len", "(", "params", ")", ">", "0", "{", "query", "=", "\"", "\"", "+", "strings", ".", "Join", "(", "params", ",", "\"", "\"", ")", "\n", "}", "\n\n", "req", ",", "err", ":=", "simpleRequest", "(", "\"", "\"", ",", "gsAccessURL", "+", "\"", "\"", "+", "bucket", "+", "\"", "\"", "+", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Cancel", "=", "ctx", ".", "Done", "(", ")", "\n", "res", ",", "err", ":=", "ctxutil", ".", "Client", "(", "ctx", ")", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "if", "res", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "Status", ")", "\n", "}", "\n\n", "var", "xres", "struct", "{", "Contents", "[", "]", "SizedObject", "\n", "}", "\n", "if", "err", "=", "xml", ".", "NewDecoder", "(", "res", ".", "Body", ")", ".", "Decode", "(", "&", "xres", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "objAttrs", ":=", "make", "(", "[", "]", "*", "storage", ".", "ObjectAttrs", ",", "len", "(", "xres", ".", "Contents", ")", ")", "\n", "for", "k", ",", "o", ":=", "range", "xres", ".", "Contents", "{", "objAttrs", "[", "k", "]", "=", "&", "storage", ".", "ObjectAttrs", "{", "Name", ":", "o", ".", "Key", ",", "Size", ":", "o", ".", "Size", ",", "}", "\n", "}", "\n\n", "return", "objAttrs", ",", "nil", "\n", "}" ]
// EnumerateObjects lists the objects in a bucket. // This function relies on the ctx oauth2.HTTPClient value being set to an OAuth2 // authorized and authenticated HTTP client. // If after is non-empty, listing will begin with lexically greater object names. // If limit is non-zero, the length of the list will be limited to that number.
[ "EnumerateObjects", "lists", "the", "objects", "in", "a", "bucket", ".", "This", "function", "relies", "on", "the", "ctx", "oauth2", ".", "HTTPClient", "value", "being", "set", "to", "an", "OAuth2", "authorized", "and", "authenticated", "HTTP", "client", ".", "If", "after", "is", "non", "-", "empty", "listing", "will", "begin", "with", "lexically", "greater", "object", "names", ".", "If", "limit", "is", "non", "-", "zero", "the", "length", "of", "the", "list", "will", "be", "limited", "to", "that", "number", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/cloud/google/gcsutil/storage.go#L136-L180
14,796
go4org/go4
cloud/cloudlaunch/cloudlaunch.go
uploadBinary
func (cl *cloudLaunch) uploadBinary() { ctx := context.Background() if cl.BinaryBucket == "" { log.Fatal("cloudlaunch: Config.BinaryBucket is empty") } stoClient, err := storage.NewClient(ctx, option.WithHTTPClient(cl.oauthClient)) if err != nil { log.Fatal(err) } w := stoClient.Bucket(cl.BinaryBucket).Object(cl.binaryObject()).NewWriter(ctx) if err != nil { log.Fatal(err) } w.ACL = []storage.ACLRule{ // If you don't give the owners access, the web UI seems to // have a bug and doesn't have access to see that it's public, so // won't render the "Shared Publicly" link. So we do that, even // though it's dumb and unnecessary otherwise: { Entity: storage.ACLEntity("project-owners-" + cl.GCEProjectID), Role: storage.RoleOwner, }, // Public, so our systemd unit can get it easily: { Entity: storage.AllUsers, Role: storage.RoleReader, }, } w.CacheControl = "no-cache" selfPath := getSelfPath() log.Printf("Uploading %q to %v", selfPath, cl.binaryURL()) f, err := os.Open(selfPath) if err != nil { log.Fatal(err) } defer f.Close() n, err := io.Copy(w, f) if err != nil { log.Fatal(err) } if err := w.Close(); err != nil { log.Fatal(err) } log.Printf("Uploaded %d bytes", n) }
go
func (cl *cloudLaunch) uploadBinary() { ctx := context.Background() if cl.BinaryBucket == "" { log.Fatal("cloudlaunch: Config.BinaryBucket is empty") } stoClient, err := storage.NewClient(ctx, option.WithHTTPClient(cl.oauthClient)) if err != nil { log.Fatal(err) } w := stoClient.Bucket(cl.BinaryBucket).Object(cl.binaryObject()).NewWriter(ctx) if err != nil { log.Fatal(err) } w.ACL = []storage.ACLRule{ // If you don't give the owners access, the web UI seems to // have a bug and doesn't have access to see that it's public, so // won't render the "Shared Publicly" link. So we do that, even // though it's dumb and unnecessary otherwise: { Entity: storage.ACLEntity("project-owners-" + cl.GCEProjectID), Role: storage.RoleOwner, }, // Public, so our systemd unit can get it easily: { Entity: storage.AllUsers, Role: storage.RoleReader, }, } w.CacheControl = "no-cache" selfPath := getSelfPath() log.Printf("Uploading %q to %v", selfPath, cl.binaryURL()) f, err := os.Open(selfPath) if err != nil { log.Fatal(err) } defer f.Close() n, err := io.Copy(w, f) if err != nil { log.Fatal(err) } if err := w.Close(); err != nil { log.Fatal(err) } log.Printf("Uploaded %d bytes", n) }
[ "func", "(", "cl", "*", "cloudLaunch", ")", "uploadBinary", "(", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "if", "cl", ".", "BinaryBucket", "==", "\"", "\"", "{", "log", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "stoClient", ",", "err", ":=", "storage", ".", "NewClient", "(", "ctx", ",", "option", ".", "WithHTTPClient", "(", "cl", ".", "oauthClient", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "w", ":=", "stoClient", ".", "Bucket", "(", "cl", ".", "BinaryBucket", ")", ".", "Object", "(", "cl", ".", "binaryObject", "(", ")", ")", ".", "NewWriter", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "w", ".", "ACL", "=", "[", "]", "storage", ".", "ACLRule", "{", "// If you don't give the owners access, the web UI seems to", "// have a bug and doesn't have access to see that it's public, so", "// won't render the \"Shared Publicly\" link. So we do that, even", "// though it's dumb and unnecessary otherwise:", "{", "Entity", ":", "storage", ".", "ACLEntity", "(", "\"", "\"", "+", "cl", ".", "GCEProjectID", ")", ",", "Role", ":", "storage", ".", "RoleOwner", ",", "}", ",", "// Public, so our systemd unit can get it easily:", "{", "Entity", ":", "storage", ".", "AllUsers", ",", "Role", ":", "storage", ".", "RoleReader", ",", "}", ",", "}", "\n", "w", ".", "CacheControl", "=", "\"", "\"", "\n", "selfPath", ":=", "getSelfPath", "(", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "selfPath", ",", "cl", ".", "binaryURL", "(", ")", ")", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "selfPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "n", ",", "err", ":=", "io", ".", "Copy", "(", "w", ",", "f", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "w", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "n", ")", "\n", "}" ]
// uploadBinary uploads the currently-running Linux binary. // It crashes if it fails.
[ "uploadBinary", "uploads", "the", "currently", "-", "running", "Linux", "binary", ".", "It", "crashes", "if", "it", "fails", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/cloud/cloudlaunch/cloudlaunch.go#L232-L276
14,797
go4org/go4
cloud/cloudlaunch/cloudlaunch.go
findIP
func (cl *cloudLaunch) findIP() string { // Try to find it by name. aggAddrList, err := cl.computeService.Addresses.AggregatedList(cl.GCEProjectID).Do() if err != nil { log.Fatal(err) } // https://godoc.org/google.golang.org/api/compute/v1#AddressAggregatedList var ip string IPLoop: for _, asl := range aggAddrList.Items { for _, addr := range asl.Addresses { log.Printf(" addr: %#v", addr) if addr.Name == cl.Name+"-ip" && addr.Status == "RESERVED" && zoneInRegion(cl.zone(), addr.Region) { ip = addr.Address break IPLoop } } } return ip }
go
func (cl *cloudLaunch) findIP() string { // Try to find it by name. aggAddrList, err := cl.computeService.Addresses.AggregatedList(cl.GCEProjectID).Do() if err != nil { log.Fatal(err) } // https://godoc.org/google.golang.org/api/compute/v1#AddressAggregatedList var ip string IPLoop: for _, asl := range aggAddrList.Items { for _, addr := range asl.Addresses { log.Printf(" addr: %#v", addr) if addr.Name == cl.Name+"-ip" && addr.Status == "RESERVED" && zoneInRegion(cl.zone(), addr.Region) { ip = addr.Address break IPLoop } } } return ip }
[ "func", "(", "cl", "*", "cloudLaunch", ")", "findIP", "(", ")", "string", "{", "// Try to find it by name.", "aggAddrList", ",", "err", ":=", "cl", ".", "computeService", ".", "Addresses", ".", "AggregatedList", "(", "cl", ".", "GCEProjectID", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "// https://godoc.org/google.golang.org/api/compute/v1#AddressAggregatedList", "var", "ip", "string", "\n", "IPLoop", ":", "for", "_", ",", "asl", ":=", "range", "aggAddrList", ".", "Items", "{", "for", "_", ",", "addr", ":=", "range", "asl", ".", "Addresses", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "addr", ".", "Name", "==", "cl", ".", "Name", "+", "\"", "\"", "&&", "addr", ".", "Status", "==", "\"", "\"", "&&", "zoneInRegion", "(", "cl", ".", "zone", "(", ")", ",", "addr", ".", "Region", ")", "{", "ip", "=", "addr", ".", "Address", "\n", "break", "IPLoop", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "ip", "\n", "}" ]
// findIP finds an IP address to use, or returns the empty string if none is found. // It tries to find a reserved one in the same region where the name of the reserved IP // is "NAME-ip" and the IP is not in use.
[ "findIP", "finds", "an", "IP", "address", "to", "use", "or", "returns", "the", "empty", "string", "if", "none", "is", "found", ".", "It", "tries", "to", "find", "a", "reserved", "one", "in", "the", "same", "region", "where", "the", "name", "of", "the", "reserved", "IP", "is", "NAME", "-", "ip", "and", "the", "IP", "is", "not", "in", "use", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/cloud/cloudlaunch/cloudlaunch.go#L308-L327
14,798
go4org/go4
cloud/cloudlaunch/cloudlaunch.go
lookupInstance
func (cl *cloudLaunch) lookupInstance() *compute.Instance { inst, err := cl.computeService.Instances.Get(cl.GCEProjectID, cl.zone(), cl.instName()).Do() if ae, ok := err.(*googleapi.Error); ok && ae.Code == 404 { return nil } else if err != nil { log.Fatalf("Instances.Get: %v", err) } return inst }
go
func (cl *cloudLaunch) lookupInstance() *compute.Instance { inst, err := cl.computeService.Instances.Get(cl.GCEProjectID, cl.zone(), cl.instName()).Do() if ae, ok := err.(*googleapi.Error); ok && ae.Code == 404 { return nil } else if err != nil { log.Fatalf("Instances.Get: %v", err) } return inst }
[ "func", "(", "cl", "*", "cloudLaunch", ")", "lookupInstance", "(", ")", "*", "compute", ".", "Instance", "{", "inst", ",", "err", ":=", "cl", ".", "computeService", ".", "Instances", ".", "Get", "(", "cl", ".", "GCEProjectID", ",", "cl", ".", "zone", "(", ")", ",", "cl", ".", "instName", "(", ")", ")", ".", "Do", "(", ")", "\n", "if", "ae", ",", "ok", ":=", "err", ".", "(", "*", "googleapi", ".", "Error", ")", ";", "ok", "&&", "ae", ".", "Code", "==", "404", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "inst", "\n", "}" ]
// returns nil if instance doesn't exist.
[ "returns", "nil", "if", "instance", "doesn", "t", "exist", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/cloud/cloudlaunch/cloudlaunch.go#L426-L434
14,799
go4org/go4
rollsum/rollsum.go
Roll
func (rs *RollSum) Roll(ch byte) { wp := &rs.window[rs.wofs] rs.add(uint32(*wp), uint32(ch)) *wp = ch rs.wofs = (rs.wofs + 1) & (windowSize - 1) }
go
func (rs *RollSum) Roll(ch byte) { wp := &rs.window[rs.wofs] rs.add(uint32(*wp), uint32(ch)) *wp = ch rs.wofs = (rs.wofs + 1) & (windowSize - 1) }
[ "func", "(", "rs", "*", "RollSum", ")", "Roll", "(", "ch", "byte", ")", "{", "wp", ":=", "&", "rs", ".", "window", "[", "rs", ".", "wofs", "]", "\n", "rs", ".", "add", "(", "uint32", "(", "*", "wp", ")", ",", "uint32", "(", "ch", ")", ")", "\n", "*", "wp", "=", "ch", "\n", "rs", ".", "wofs", "=", "(", "rs", ".", "wofs", "+", "1", ")", "&", "(", "windowSize", "-", "1", ")", "\n", "}" ]
// Roll adds ch to the rolling sum.
[ "Roll", "adds", "ch", "to", "the", "rolling", "sum", "." ]
94abd6928b1da39b1d757b60c93fb2419c409fa1
https://github.com/go4org/go4/blob/94abd6928b1da39b1d757b60c93fb2419c409fa1/rollsum/rollsum.go#L54-L59