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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
1,900
ajg/form
encode.go
Encode
func (e Encoder) Encode(dst interface{}) error { v := reflect.ValueOf(dst) n, err := encodeToNode(v, e.z) if err != nil { return err } s := n.values(e.d, e.e).Encode() l, err := io.WriteString(e.w, s) switch { case err != nil: return err case l != len(s): return errors.New("could not write data completely") } return nil }
go
func (e Encoder) Encode(dst interface{}) error { v := reflect.ValueOf(dst) n, err := encodeToNode(v, e.z) if err != nil { return err } s := n.values(e.d, e.e).Encode() l, err := io.WriteString(e.w, s) switch { case err != nil: return err case l != len(s): return errors.New("could not write data completely") } return nil }
[ "func", "(", "e", "Encoder", ")", "Encode", "(", "dst", "interface", "{", "}", ")", "error", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", "\n", "n", ",", "err", ":=", "encodeToNode", "(", "v", ",", "e", ".", "z", ")", "\n", "if",...
// Encode encodes dst as form and writes it out using the Encoder's Writer.
[ "Encode", "encodes", "dst", "as", "form", "and", "writes", "it", "out", "using", "the", "Encoder", "s", "Writer", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/encode.go#L51-L66
1,901
ajg/form
encode.go
EncodeToString
func EncodeToString(dst interface{}) (string, error) { v := reflect.ValueOf(dst) n, err := encodeToNode(v, false) if err != nil { return "", err } vs := n.values(defaultDelimiter, defaultEscape) return vs.Encode(), nil }
go
func EncodeToString(dst interface{}) (string, error) { v := reflect.ValueOf(dst) n, err := encodeToNode(v, false) if err != nil { return "", err } vs := n.values(defaultDelimiter, defaultEscape) return vs.Encode(), nil }
[ "func", "EncodeToString", "(", "dst", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", "\n", "n", ",", "err", ":=", "encodeToNode", "(", "v", ",", "false", ")", "\n", "if", ...
// EncodeToString encodes dst as a form and returns it as a string.
[ "EncodeToString", "encodes", "dst", "as", "a", "form", "and", "returns", "it", "as", "a", "string", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/encode.go#L69-L77
1,902
ajg/form
encode.go
EncodeToValues
func EncodeToValues(dst interface{}) (url.Values, error) { v := reflect.ValueOf(dst) n, err := encodeToNode(v, false) if err != nil { return nil, err } vs := n.values(defaultDelimiter, defaultEscape) return vs, nil }
go
func EncodeToValues(dst interface{}) (url.Values, error) { v := reflect.ValueOf(dst) n, err := encodeToNode(v, false) if err != nil { return nil, err } vs := n.values(defaultDelimiter, defaultEscape) return vs, nil }
[ "func", "EncodeToValues", "(", "dst", "interface", "{", "}", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", "\n", "n", ",", "err", ":=", "encodeToNode", "(", "v", ",", "false", ")", ...
// EncodeToValues encodes dst as a form and returns it as Values.
[ "EncodeToValues", "encodes", "dst", "as", "a", "form", "and", "returns", "it", "as", "Values", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/encode.go#L80-L88
1,903
ajg/form
encode.go
canIndexOrdinally
func canIndexOrdinally(v reflect.Value) bool { if !v.IsValid() { return false } switch t := v.Type(); t.Kind() { case reflect.Ptr, reflect.Interface: return canIndexOrdinally(v.Elem()) case reflect.Slice, reflect.Array: return true } return false }
go
func canIndexOrdinally(v reflect.Value) bool { if !v.IsValid() { return false } switch t := v.Type(); t.Kind() { case reflect.Ptr, reflect.Interface: return canIndexOrdinally(v.Elem()) case reflect.Slice, reflect.Array: return true } return false }
[ "func", "canIndexOrdinally", "(", "v", "reflect", ".", "Value", ")", "bool", "{", "if", "!", "v", ".", "IsValid", "(", ")", "{", "return", "false", "\n", "}", "\n", "switch", "t", ":=", "v", ".", "Type", "(", ")", ";", "t", ".", "Kind", "(", ")...
// canIndexOrdinally returns whether a value contains an ordered sequence of elements.
[ "canIndexOrdinally", "returns", "whether", "a", "value", "contains", "an", "ordered", "sequence", "of", "elements", "." ]
5c4e22684113ffc2a77577c178189940925f9aef
https://github.com/ajg/form/blob/5c4e22684113ffc2a77577c178189940925f9aef/encode.go#L250-L261
1,904
valyala/tcplisten
tcplisten.go
NewListener
func (cfg *Config) NewListener(network, addr string) (net.Listener, error) { sa, soType, err := getSockaddr(network, addr) if err != nil { return nil, err } fd, err := newSocketCloexec(soType, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) if err != nil { return nil, err } if err = cfg.fdSetup(fd, sa, addr); err != nil { syscall.Close(fd) return nil, err } name := fmt.Sprintf("reuseport.%d.%s.%s", os.Getpid(), network, addr) file := os.NewFile(uintptr(fd), name) ln, err := net.FileListener(file) if err != nil { file.Close() return nil, err } if err = file.Close(); err != nil { ln.Close() return nil, err } return ln, nil }
go
func (cfg *Config) NewListener(network, addr string) (net.Listener, error) { sa, soType, err := getSockaddr(network, addr) if err != nil { return nil, err } fd, err := newSocketCloexec(soType, syscall.SOCK_STREAM, syscall.IPPROTO_TCP) if err != nil { return nil, err } if err = cfg.fdSetup(fd, sa, addr); err != nil { syscall.Close(fd) return nil, err } name := fmt.Sprintf("reuseport.%d.%s.%s", os.Getpid(), network, addr) file := os.NewFile(uintptr(fd), name) ln, err := net.FileListener(file) if err != nil { file.Close() return nil, err } if err = file.Close(); err != nil { ln.Close() return nil, err } return ln, nil }
[ "func", "(", "cfg", "*", "Config", ")", "NewListener", "(", "network", ",", "addr", "string", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "sa", ",", "soType", ",", "err", ":=", "getSockaddr", "(", "network", ",", "addr", ")", "\n", "i...
// NewListener returns TCP listener with options set in the Config. // // The function may be called many times for creating distinct listeners // with the given config. // // Only tcp4 and tcp6 networks are supported.
[ "NewListener", "returns", "TCP", "listener", "with", "options", "set", "in", "the", "Config", ".", "The", "function", "may", "be", "called", "many", "times", "for", "creating", "distinct", "listeners", "with", "the", "given", "config", ".", "Only", "tcp4", "...
ceec8f93295a060cdb565ec25e4ccf17941dbd55
https://github.com/valyala/tcplisten/blob/ceec8f93295a060cdb565ec25e4ccf17941dbd55/tcplisten.go#L51-L81
1,905
hashicorp/go-cleanhttp
cleanhttp.go
DefaultTransport
func DefaultTransport() *http.Transport { transport := DefaultPooledTransport() transport.DisableKeepAlives = true transport.MaxIdleConnsPerHost = -1 return transport }
go
func DefaultTransport() *http.Transport { transport := DefaultPooledTransport() transport.DisableKeepAlives = true transport.MaxIdleConnsPerHost = -1 return transport }
[ "func", "DefaultTransport", "(", ")", "*", "http", ".", "Transport", "{", "transport", ":=", "DefaultPooledTransport", "(", ")", "\n", "transport", ".", "DisableKeepAlives", "=", "true", "\n", "transport", ".", "MaxIdleConnsPerHost", "=", "-", "1", "\n", "retu...
// DefaultTransport returns a new http.Transport with similar default values to // http.DefaultTransport, but with idle connections and keepalives disabled.
[ "DefaultTransport", "returns", "a", "new", "http", ".", "Transport", "with", "similar", "default", "values", "to", "http", ".", "DefaultTransport", "but", "with", "idle", "connections", "and", "keepalives", "disabled", "." ]
d3fcbee8e1810ecee4bdbf415f42f84cfd0e3361
https://github.com/hashicorp/go-cleanhttp/blob/d3fcbee8e1810ecee4bdbf415f42f84cfd0e3361/cleanhttp.go#L12-L17
1,906
hashicorp/go-cleanhttp
handlers.go
PrintablePathCheckHandler
func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler { // Nil-check on input to make it optional if input == nil { input = &HandlerInput{ ErrStatus: http.StatusBadRequest, } } // Default to http.StatusBadRequest on error if input.ErrStatus == 0 { input.ErrStatus = http.StatusBadRequest } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r != nil { // Check URL path for non-printable characters idx := strings.IndexFunc(r.URL.Path, func(c rune) bool { return !unicode.IsPrint(c) }) if idx != -1 { w.WriteHeader(input.ErrStatus) return } if next != nil { next.ServeHTTP(w, r) } } return }) }
go
func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler { // Nil-check on input to make it optional if input == nil { input = &HandlerInput{ ErrStatus: http.StatusBadRequest, } } // Default to http.StatusBadRequest on error if input.ErrStatus == 0 { input.ErrStatus = http.StatusBadRequest } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r != nil { // Check URL path for non-printable characters idx := strings.IndexFunc(r.URL.Path, func(c rune) bool { return !unicode.IsPrint(c) }) if idx != -1 { w.WriteHeader(input.ErrStatus) return } if next != nil { next.ServeHTTP(w, r) } } return }) }
[ "func", "PrintablePathCheckHandler", "(", "next", "http", ".", "Handler", ",", "input", "*", "HandlerInput", ")", "http", ".", "Handler", "{", "// Nil-check on input to make it optional", "if", "input", "==", "nil", "{", "input", "=", "&", "HandlerInput", "{", "...
// PrintablePathCheckHandler is a middleware that ensures the request path // contains only printable runes.
[ "PrintablePathCheckHandler", "is", "a", "middleware", "that", "ensures", "the", "request", "path", "contains", "only", "printable", "runes", "." ]
d3fcbee8e1810ecee4bdbf415f42f84cfd0e3361
https://github.com/hashicorp/go-cleanhttp/blob/d3fcbee8e1810ecee4bdbf415f42f84cfd0e3361/handlers.go#L16-L48
1,907
monoculum/formam
formam.go
find
func (m pathMaps) find(id reflect.Value, key string) *pathMap { for i := range m { if m[i].ma == id && m[i].key == key { return m[i] } } return nil }
go
func (m pathMaps) find(id reflect.Value, key string) *pathMap { for i := range m { if m[i].ma == id && m[i].key == key { return m[i] } } return nil }
[ "func", "(", "m", "pathMaps", ")", "find", "(", "id", "reflect", ".", "Value", ",", "key", "string", ")", "*", "pathMap", "{", "for", "i", ":=", "range", "m", "{", "if", "m", "[", "i", "]", ".", "ma", "==", "id", "&&", "m", "[", "i", "]", "...
// find finds and gets the value by the given key
[ "find", "finds", "and", "gets", "the", "value", "by", "the", "given", "key" ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L28-L35
1,908
monoculum/formam
formam.go
RegisterCustomType
func (dec *Decoder) RegisterCustomType(fn DecodeCustomTypeFunc, types []interface{}, fields []interface{}) *Decoder { if dec.customTypes == nil { dec.customTypes = make(map[reflect.Type]*decodeCustomType, 100) } lenFields := len(fields) for i := range types { typ := reflect.TypeOf(types[i]) if dec.customTypes[typ] == nil { dec.customTypes[typ] = &decodeCustomType{fun: fn, fields: make([]*decodeCustomTypeField, 0, lenFields)} } if lenFields > 0 { for j := range fields { val := reflect.ValueOf(fields[j]) field := &decodeCustomTypeField{field: val, fun: fn} dec.customTypes[typ].fields = append(dec.customTypes[typ].fields, field) } } } return dec }
go
func (dec *Decoder) RegisterCustomType(fn DecodeCustomTypeFunc, types []interface{}, fields []interface{}) *Decoder { if dec.customTypes == nil { dec.customTypes = make(map[reflect.Type]*decodeCustomType, 100) } lenFields := len(fields) for i := range types { typ := reflect.TypeOf(types[i]) if dec.customTypes[typ] == nil { dec.customTypes[typ] = &decodeCustomType{fun: fn, fields: make([]*decodeCustomTypeField, 0, lenFields)} } if lenFields > 0 { for j := range fields { val := reflect.ValueOf(fields[j]) field := &decodeCustomTypeField{field: val, fun: fn} dec.customTypes[typ].fields = append(dec.customTypes[typ].fields, field) } } } return dec }
[ "func", "(", "dec", "*", "Decoder", ")", "RegisterCustomType", "(", "fn", "DecodeCustomTypeFunc", ",", "types", "[", "]", "interface", "{", "}", ",", "fields", "[", "]", "interface", "{", "}", ")", "*", "Decoder", "{", "if", "dec", ".", "customTypes", ...
// RegisterCustomType registers a functions for decoding custom types.
[ "RegisterCustomType", "registers", "a", "functions", "for", "decoding", "custom", "types", "." ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L85-L104
1,909
monoculum/formam
formam.go
NewDecoder
func NewDecoder(opts *DecoderOptions) *Decoder { dec := &Decoder{opts: opts} if dec.opts == nil { dec.opts = &DecoderOptions{} } if dec.opts.TagName == "" { dec.opts.TagName = tagName } return dec }
go
func NewDecoder(opts *DecoderOptions) *Decoder { dec := &Decoder{opts: opts} if dec.opts == nil { dec.opts = &DecoderOptions{} } if dec.opts.TagName == "" { dec.opts.TagName = tagName } return dec }
[ "func", "NewDecoder", "(", "opts", "*", "DecoderOptions", ")", "*", "Decoder", "{", "dec", ":=", "&", "Decoder", "{", "opts", ":", "opts", "}", "\n", "if", "dec", ".", "opts", "==", "nil", "{", "dec", ".", "opts", "=", "&", "DecoderOptions", "{", "...
// NewDecoder creates a new instance of Decoder.
[ "NewDecoder", "creates", "a", "new", "instance", "of", "Decoder", "." ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L107-L116
1,910
monoculum/formam
formam.go
init
func (dec Decoder) init() error { // iterate over the form's values and decode it for k, v := range dec.formValues { dec.path = k dec.values = v dec.curr = dec.main if err := dec.analyzePath(); err != nil { if dec.curr.Kind() == reflect.Struct && dec.opts.IgnoreUnknownKeys { continue } return err } } // set values of maps for _, v := range dec.maps { key := v.ma.Type().Key() ptr := false // check if the key implements the UnmarshalText interface var val reflect.Value if key.Kind() == reflect.Ptr { ptr = true val = reflect.New(key.Elem()) } else { val = reflect.New(key).Elem() } // decode key dec.path = v.path dec.field = v.path dec.values = []string{v.key} dec.curr = val //dec.isKey = true if err := dec.decode(); err != nil { return err } // check if the key is a pointer or not. And if it is, then get its address if ptr && dec.curr.Kind() != reflect.Ptr { dec.curr = dec.curr.Addr() } // set key with its value v.ma.SetMapIndex(dec.curr, v.value) } return nil }
go
func (dec Decoder) init() error { // iterate over the form's values and decode it for k, v := range dec.formValues { dec.path = k dec.values = v dec.curr = dec.main if err := dec.analyzePath(); err != nil { if dec.curr.Kind() == reflect.Struct && dec.opts.IgnoreUnknownKeys { continue } return err } } // set values of maps for _, v := range dec.maps { key := v.ma.Type().Key() ptr := false // check if the key implements the UnmarshalText interface var val reflect.Value if key.Kind() == reflect.Ptr { ptr = true val = reflect.New(key.Elem()) } else { val = reflect.New(key).Elem() } // decode key dec.path = v.path dec.field = v.path dec.values = []string{v.key} dec.curr = val //dec.isKey = true if err := dec.decode(); err != nil { return err } // check if the key is a pointer or not. And if it is, then get its address if ptr && dec.curr.Kind() != reflect.Ptr { dec.curr = dec.curr.Addr() } // set key with its value v.ma.SetMapIndex(dec.curr, v.value) } return nil }
[ "func", "(", "dec", "Decoder", ")", "init", "(", ")", "error", "{", "// iterate over the form's values and decode it", "for", "k", ",", "v", ":=", "range", "dec", ".", "formValues", "{", "dec", ".", "path", "=", "k", "\n", "dec", ".", "values", "=", "v",...
// init initializes the decoding
[ "init", "initializes", "the", "decoding" ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L148-L190
1,911
monoculum/formam
formam.go
analyzePath
func (dec *Decoder) analyzePath() (err error) { inBracket := false bracketClosed := false lastPos := 0 endPos := 0 // parse path for i, char := range []byte(dec.path) { if char == '[' && inBracket == false { // found an opening bracket bracketClosed = false inBracket = true dec.field = dec.path[lastPos:i] lastPos = i + 1 continue } else if inBracket { // it is inside of bracket, so get its value if char == ']' { // found an closing bracket, so it will be recently close, so put as true the bracketClosed // and put as false inBracket and pass the value of bracket to dec.key inBracket = false bracketClosed = true dec.bracket = dec.path[lastPos:endPos] lastPos = i + 1 if err = dec.traverse(); err != nil { return } } else { // still inside the bracket, so to save the end position endPos = i + 1 } continue } else if !inBracket { // not found any bracket, so try found a field if char == '.' { // found a field, we need to know if the field is next of a closing bracket, // for example: [0].Field if bracketClosed { bracketClosed = false lastPos = i + 1 continue } // found a field, but is not next of a closing bracket, for example: Field1.Field2 dec.field = dec.path[lastPos:i] //dec.field = tmp[:i] lastPos = i + 1 if err = dec.traverse(); err != nil { return } } continue } } // last field of path dec.field = dec.path[lastPos:] return dec.end() }
go
func (dec *Decoder) analyzePath() (err error) { inBracket := false bracketClosed := false lastPos := 0 endPos := 0 // parse path for i, char := range []byte(dec.path) { if char == '[' && inBracket == false { // found an opening bracket bracketClosed = false inBracket = true dec.field = dec.path[lastPos:i] lastPos = i + 1 continue } else if inBracket { // it is inside of bracket, so get its value if char == ']' { // found an closing bracket, so it will be recently close, so put as true the bracketClosed // and put as false inBracket and pass the value of bracket to dec.key inBracket = false bracketClosed = true dec.bracket = dec.path[lastPos:endPos] lastPos = i + 1 if err = dec.traverse(); err != nil { return } } else { // still inside the bracket, so to save the end position endPos = i + 1 } continue } else if !inBracket { // not found any bracket, so try found a field if char == '.' { // found a field, we need to know if the field is next of a closing bracket, // for example: [0].Field if bracketClosed { bracketClosed = false lastPos = i + 1 continue } // found a field, but is not next of a closing bracket, for example: Field1.Field2 dec.field = dec.path[lastPos:i] //dec.field = tmp[:i] lastPos = i + 1 if err = dec.traverse(); err != nil { return } } continue } } // last field of path dec.field = dec.path[lastPos:] return dec.end() }
[ "func", "(", "dec", "*", "Decoder", ")", "analyzePath", "(", ")", "(", "err", "error", ")", "{", "inBracket", ":=", "false", "\n", "bracketClosed", ":=", "false", "\n", "lastPos", ":=", "0", "\n", "endPos", ":=", "0", "\n\n", "// parse path", "for", "i...
// analyzePath analyzes the current path to walk through it
[ "analyzePath", "analyzes", "the", "current", "path", "to", "walk", "through", "it" ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L193-L250
1,912
monoculum/formam
formam.go
findStructField
func (dec *Decoder) findStructField() error { var anon reflect.Value num := dec.curr.NumField() for i := 0; i < num; i++ { field := dec.curr.Type().Field(i) if field.Name == dec.field { tag := field.Tag.Get(dec.opts.TagName) if tag == "-" { // skip this field return nil } // check if the field's name is equal dec.curr = dec.curr.Field(i) return nil } else if field.Anonymous { // if the field is a anonymous struct, then iterate over its fields tmp := dec.curr dec.curr = dec.curr.FieldByIndex(field.Index) if dec.curr.Kind() == reflect.Ptr { if dec.curr.IsNil() { dec.curr.Set(reflect.New(dec.curr.Type().Elem())) } dec.curr = dec.curr.Elem() } if err := dec.findStructField(); err != nil { dec.curr = tmp continue } // field in anonymous struct is found, // but first it should found the field in the rest of struct // (a field with same name in the current struct should have preference over anonymous struct) anon = dec.curr dec.curr = tmp } else if dec.field == getTagName(field.Tag, dec.opts.TagName) { // is not found yet, then retry by its tag name "formam" dec.curr = dec.curr.Field(i) return nil } } if anon.IsValid() { dec.curr = anon return nil } if dec.opts.IgnoreUnknownKeys { return nil } return newError("could not find the field %q in the path %q", dec.field, dec.path) }
go
func (dec *Decoder) findStructField() error { var anon reflect.Value num := dec.curr.NumField() for i := 0; i < num; i++ { field := dec.curr.Type().Field(i) if field.Name == dec.field { tag := field.Tag.Get(dec.opts.TagName) if tag == "-" { // skip this field return nil } // check if the field's name is equal dec.curr = dec.curr.Field(i) return nil } else if field.Anonymous { // if the field is a anonymous struct, then iterate over its fields tmp := dec.curr dec.curr = dec.curr.FieldByIndex(field.Index) if dec.curr.Kind() == reflect.Ptr { if dec.curr.IsNil() { dec.curr.Set(reflect.New(dec.curr.Type().Elem())) } dec.curr = dec.curr.Elem() } if err := dec.findStructField(); err != nil { dec.curr = tmp continue } // field in anonymous struct is found, // but first it should found the field in the rest of struct // (a field with same name in the current struct should have preference over anonymous struct) anon = dec.curr dec.curr = tmp } else if dec.field == getTagName(field.Tag, dec.opts.TagName) { // is not found yet, then retry by its tag name "formam" dec.curr = dec.curr.Field(i) return nil } } if anon.IsValid() { dec.curr = anon return nil } if dec.opts.IgnoreUnknownKeys { return nil } return newError("could not find the field %q in the path %q", dec.field, dec.path) }
[ "func", "(", "dec", "*", "Decoder", ")", "findStructField", "(", ")", "error", "{", "var", "anon", "reflect", ".", "Value", "\n\n", "num", ":=", "dec", ".", "curr", ".", "NumField", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "num", ";"...
// findStructField finds a field by its name, if it is not found, // then retry the search examining the tag "formam" of every field of struct
[ "findStructField", "finds", "a", "field", "by", "its", "name", "if", "it", "is", "not", "found", "then", "retry", "the", "search", "examining", "the", "tag", "formam", "of", "every", "field", "of", "struct" ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L499-L549
1,913
monoculum/formam
formam.go
expandSlice
func (dec *Decoder) expandSlice(length int) { n := reflect.MakeSlice(dec.curr.Type(), length, length) reflect.Copy(n, dec.curr) dec.curr.Set(n) }
go
func (dec *Decoder) expandSlice(length int) { n := reflect.MakeSlice(dec.curr.Type(), length, length) reflect.Copy(n, dec.curr) dec.curr.Set(n) }
[ "func", "(", "dec", "*", "Decoder", ")", "expandSlice", "(", "length", "int", ")", "{", "n", ":=", "reflect", ".", "MakeSlice", "(", "dec", ".", "curr", ".", "Type", "(", ")", ",", "length", ",", "length", ")", "\n", "reflect", ".", "Copy", "(", ...
// expandSlice expands the length and capacity of the current slice
[ "expandSlice", "expands", "the", "length", "and", "capacity", "of", "the", "current", "slice" ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L552-L556
1,914
monoculum/formam
formam.go
isCustomType
func (dec *Decoder) isCustomType() (bool, error) { if dec.customTypes == nil { return false, nil } if v, ok := dec.customTypes[dec.curr.Type()]; ok { if len(v.fields) > 0 { for i := range v.fields { // check if the current field is registered // in the fields of the custom type if v.fields[i].field.Elem() == dec.curr { va, err := v.fields[i].fun(dec.values) if err != nil { return true, err } dec.curr.Set(reflect.ValueOf(va)) return true, nil } } } // check if the default function exists for fields not specific if v.fun != nil { va, err := v.fun(dec.values) if err != nil { return true, err } dec.curr.Set(reflect.ValueOf(va)) return true, nil } } return false, nil }
go
func (dec *Decoder) isCustomType() (bool, error) { if dec.customTypes == nil { return false, nil } if v, ok := dec.customTypes[dec.curr.Type()]; ok { if len(v.fields) > 0 { for i := range v.fields { // check if the current field is registered // in the fields of the custom type if v.fields[i].field.Elem() == dec.curr { va, err := v.fields[i].fun(dec.values) if err != nil { return true, err } dec.curr.Set(reflect.ValueOf(va)) return true, nil } } } // check if the default function exists for fields not specific if v.fun != nil { va, err := v.fun(dec.values) if err != nil { return true, err } dec.curr.Set(reflect.ValueOf(va)) return true, nil } } return false, nil }
[ "func", "(", "dec", "*", "Decoder", ")", "isCustomType", "(", ")", "(", "bool", ",", "error", ")", "{", "if", "dec", ".", "customTypes", "==", "nil", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "dec", ".", "...
// isCustomType checks if the field's type to decode has a custom type registered
[ "isCustomType", "checks", "if", "the", "field", "s", "type", "to", "decode", "has", "a", "custom", "type", "registered" ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L572-L602
1,915
monoculum/formam
formam.go
isUnmarshalText
func (dec *Decoder) isUnmarshalText(v reflect.Value) (bool, error) { // check if implements the interface m, ok := v.Interface().(encoding.TextUnmarshaler) addr := v.CanAddr() if !ok && !addr { return false, nil } else if addr { return dec.isUnmarshalText(v.Addr()) } // skip if the type is time.Time n := v.Type() if n.ConvertibleTo(typeTime) || n.ConvertibleTo(typeTimePtr) { return false, nil } // return result return true, m.UnmarshalText([]byte(dec.values[0])) }
go
func (dec *Decoder) isUnmarshalText(v reflect.Value) (bool, error) { // check if implements the interface m, ok := v.Interface().(encoding.TextUnmarshaler) addr := v.CanAddr() if !ok && !addr { return false, nil } else if addr { return dec.isUnmarshalText(v.Addr()) } // skip if the type is time.Time n := v.Type() if n.ConvertibleTo(typeTime) || n.ConvertibleTo(typeTimePtr) { return false, nil } // return result return true, m.UnmarshalText([]byte(dec.values[0])) }
[ "func", "(", "dec", "*", "Decoder", ")", "isUnmarshalText", "(", "v", "reflect", ".", "Value", ")", "(", "bool", ",", "error", ")", "{", "// check if implements the interface", "m", ",", "ok", ":=", "v", ".", "Interface", "(", ")", ".", "(", "encoding", ...
// isUnmarshalText returns a boolean and error. The boolean is true if the // field's type implements TextUnmarshaler, and false if not.
[ "isUnmarshalText", "returns", "a", "boolean", "and", "error", ".", "The", "boolean", "is", "true", "if", "the", "field", "s", "type", "implements", "TextUnmarshaler", "and", "false", "if", "not", "." ]
bc555adff0cdad744402d98133e4de9d2fe9b099
https://github.com/monoculum/formam/blob/bc555adff0cdad744402d98133e4de9d2fe9b099/formam.go#L611-L627
1,916
moul/http2curl
http2curl.go
append
func (c *CurlCommand) append(newSlice ...string) { c.slice = append(c.slice, newSlice...) }
go
func (c *CurlCommand) append(newSlice ...string) { c.slice = append(c.slice, newSlice...) }
[ "func", "(", "c", "*", "CurlCommand", ")", "append", "(", "newSlice", "...", "string", ")", "{", "c", ".", "slice", "=", "append", "(", "c", ".", "slice", ",", "newSlice", "...", ")", "\n", "}" ]
// append appends a string to the CurlCommand
[ "append", "appends", "a", "string", "to", "the", "CurlCommand" ]
faeffb3553568c6ecaa9c103c09dea941ca9c570
https://github.com/moul/http2curl/blob/faeffb3553568c6ecaa9c103c09dea941ca9c570/http2curl.go#L19-L21
1,917
moul/http2curl
http2curl.go
GetCurlCommand
func GetCurlCommand(req *http.Request) (*CurlCommand, error) { command := CurlCommand{} command.append("curl") command.append("-X", bashEscape(req.Method)) if req.Body != nil { body, err := ioutil.ReadAll(req.Body) if err != nil { return nil, err } req.Body = nopCloser{bytes.NewBuffer(body)} bodyEscaped := bashEscape(string(body)) command.append("-d", bodyEscaped) } var keys []string for k := range req.Header { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { command.append("-H", bashEscape(fmt.Sprintf("%s: %s", k, strings.Join(req.Header[k], " ")))) } command.append(bashEscape(req.URL.String())) return &command, nil }
go
func GetCurlCommand(req *http.Request) (*CurlCommand, error) { command := CurlCommand{} command.append("curl") command.append("-X", bashEscape(req.Method)) if req.Body != nil { body, err := ioutil.ReadAll(req.Body) if err != nil { return nil, err } req.Body = nopCloser{bytes.NewBuffer(body)} bodyEscaped := bashEscape(string(body)) command.append("-d", bodyEscaped) } var keys []string for k := range req.Header { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { command.append("-H", bashEscape(fmt.Sprintf("%s: %s", k, strings.Join(req.Header[k], " ")))) } command.append(bashEscape(req.URL.String())) return &command, nil }
[ "func", "GetCurlCommand", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "CurlCommand", ",", "error", ")", "{", "command", ":=", "CurlCommand", "{", "}", "\n\n", "command", ".", "append", "(", "\"", "\"", ")", "\n\n", "command", ".", "append",...
// GetCurlCommand returns a CurlCommand corresponding to an http.Request
[ "GetCurlCommand", "returns", "a", "CurlCommand", "corresponding", "to", "an", "http", ".", "Request" ]
faeffb3553568c6ecaa9c103c09dea941ca9c570
https://github.com/moul/http2curl/blob/faeffb3553568c6ecaa9c103c09dea941ca9c570/http2curl.go#L40-L71
1,918
bogem/id3v2
id3v2.go
Open
func Open(name string, opts Options) (*Tag, error) { file, err := os.Open(name) if err != nil { return nil, err } return ParseReader(file, opts) }
go
func Open(name string, opts Options) (*Tag, error) { file, err := os.Open(name) if err != nil { return nil, err } return ParseReader(file, opts) }
[ "func", "Open", "(", "name", "string", ",", "opts", "Options", ")", "(", "*", "Tag", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", ...
// Open opens file with name and passes it to OpenFile. // If there is no tag in file, it will create new one with version ID3v2.4.
[ "Open", "opens", "file", "with", "name", "and", "passes", "it", "to", "OpenFile", ".", "If", "there", "is", "no", "tag", "in", "file", "it", "will", "create", "new", "one", "with", "version", "ID3v2", ".", "4", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/id3v2.go#L40-L46
1,919
bogem/id3v2
id3v2.go
ParseReader
func ParseReader(rd io.Reader, opts Options) (*Tag, error) { tag := NewEmptyTag() err := tag.parse(rd, opts) return tag, err }
go
func ParseReader(rd io.Reader, opts Options) (*Tag, error) { tag := NewEmptyTag() err := tag.parse(rd, opts) return tag, err }
[ "func", "ParseReader", "(", "rd", "io", ".", "Reader", ",", "opts", "Options", ")", "(", "*", "Tag", ",", "error", ")", "{", "tag", ":=", "NewEmptyTag", "(", ")", "\n", "err", ":=", "tag", ".", "parse", "(", "rd", ",", "opts", ")", "\n", "return"...
// ParseReader parses rd and finds tag in it considering opts. // If there is no tag in rd, it will create new one with version ID3v2.4.
[ "ParseReader", "parses", "rd", "and", "finds", "tag", "in", "it", "considering", "opts", ".", "If", "there", "is", "no", "tag", "in", "rd", "it", "will", "create", "new", "one", "with", "version", "ID3v2", ".", "4", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/id3v2.go#L50-L54
1,920
bogem/id3v2
parse.go
parse
func (tag *Tag) parse(rd io.Reader, opts Options) error { if rd == nil { return errors.New("rd is nil") } header, err := parseHeader(rd) if err == errNoTag || err == io.EOF { tag.init(rd, 0, 4) return nil } if err != nil { return fmt.Errorf("error by parsing tag header: %v", err) } if header.Version < 3 { return ErrUnsupportedVersion } tag.init(rd, tagHeaderSize+header.FramesSize, header.Version) if !opts.Parse { return nil } return tag.parseFrames(opts) }
go
func (tag *Tag) parse(rd io.Reader, opts Options) error { if rd == nil { return errors.New("rd is nil") } header, err := parseHeader(rd) if err == errNoTag || err == io.EOF { tag.init(rd, 0, 4) return nil } if err != nil { return fmt.Errorf("error by parsing tag header: %v", err) } if header.Version < 3 { return ErrUnsupportedVersion } tag.init(rd, tagHeaderSize+header.FramesSize, header.Version) if !opts.Parse { return nil } return tag.parseFrames(opts) }
[ "func", "(", "tag", "*", "Tag", ")", "parse", "(", "rd", "io", ".", "Reader", ",", "opts", "Options", ")", "error", "{", "if", "rd", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "header", ",", "err"...
// parse finds ID3v2 tag in rd and parses it to tag considering opts. // If rd is smaller than expected, it returns ErrSmallHeaderSize.
[ "parse", "finds", "ID3v2", "tag", "in", "rd", "and", "parses", "it", "to", "tag", "considering", "opts", ".", "If", "rd", "is", "smaller", "than", "expected", "it", "returns", "ErrSmallHeaderSize", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/parse.go#L28-L50
1,921
bogem/id3v2
parse.go
skipReaderBuf
func skipReaderBuf(rd io.Reader, buf []byte) error { for { _, err := rd.Read(buf) if err == io.EOF { break } if err != nil { return err } } return nil }
go
func skipReaderBuf(rd io.Reader, buf []byte) error { for { _, err := rd.Read(buf) if err == io.EOF { break } if err != nil { return err } } return nil }
[ "func", "skipReaderBuf", "(", "rd", "io", ".", "Reader", ",", "buf", "[", "]", "byte", ")", "error", "{", "for", "{", "_", ",", "err", ":=", "rd", ".", "Read", "(", "buf", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}...
// skipReaderBuf just reads rd until io.EOF.
[ "skipReaderBuf", "just", "reads", "rd", "until", "io", ".", "EOF", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/parse.go#L161-L172
1,922
bogem/id3v2
header.go
parseHeader
func parseHeader(rd io.Reader) (tagHeader, error) { var header tagHeader data := make([]byte, tagHeaderSize) n, err := rd.Read(data) if err != nil { return header, err } if n < tagHeaderSize { return header, ErrSmallHeaderSize } if !isID3Tag(data[0:3]) { return header, errNoTag } header.Version = data[3] // Tag header size is always synchsafe. size, err := parseSize(data[6:], true) if err != nil { return header, err } header.FramesSize = size return header, nil }
go
func parseHeader(rd io.Reader) (tagHeader, error) { var header tagHeader data := make([]byte, tagHeaderSize) n, err := rd.Read(data) if err != nil { return header, err } if n < tagHeaderSize { return header, ErrSmallHeaderSize } if !isID3Tag(data[0:3]) { return header, errNoTag } header.Version = data[3] // Tag header size is always synchsafe. size, err := parseSize(data[6:], true) if err != nil { return header, err } header.FramesSize = size return header, nil }
[ "func", "parseHeader", "(", "rd", "io", ".", "Reader", ")", "(", "tagHeader", ",", "error", ")", "{", "var", "header", "tagHeader", "\n\n", "data", ":=", "make", "(", "[", "]", "byte", ",", "tagHeaderSize", ")", "\n", "n", ",", "err", ":=", "rd", "...
// parseHeader parses tag header in rd. // If there is no tag in rd, it returns errNoTag. // If rd is smaller than expected, it returns ErrSmallHeaderSize.
[ "parseHeader", "parses", "tag", "header", "in", "rd", ".", "If", "there", "is", "no", "tag", "in", "rd", "it", "returns", "errNoTag", ".", "If", "rd", "is", "smaller", "than", "expected", "it", "returns", "ErrSmallHeaderSize", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/header.go#L30-L56
1,923
bogem/id3v2
buf_reader.go
readTillDelim
func (br *bufReader) readTillDelim(delim byte) ([]byte, error) { read, err := br.buf.ReadBytes(delim) if err != nil || len(read) == 0 { return read, err } err = br.buf.UnreadByte() return read[:len(read)-1], err }
go
func (br *bufReader) readTillDelim(delim byte) ([]byte, error) { read, err := br.buf.ReadBytes(delim) if err != nil || len(read) == 0 { return read, err } err = br.buf.UnreadByte() return read[:len(read)-1], err }
[ "func", "(", "br", "*", "bufReader", ")", "readTillDelim", "(", "delim", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "read", ",", "err", ":=", "br", ".", "buf", ".", "ReadBytes", "(", "delim", ")", "\n", "if", "err", "!=", "nil", ...
// readTillDelim reads until the first occurrence of delim in the input, // returning a slice containing the data up to and NOT including the delim. // If ReadTillDelim encounters an error before finding a delimiter, // it returns the data read before the error and the error itself. // ReadTillDelim returns err != nil if and only if ReadTillDelim didn't find // delim.
[ "readTillDelim", "reads", "until", "the", "first", "occurrence", "of", "delim", "in", "the", "input", "returning", "a", "slice", "containing", "the", "data", "up", "to", "and", "NOT", "including", "the", "delim", ".", "If", "ReadTillDelim", "encounters", "an",...
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/buf_reader.go#L109-L116
1,924
bogem/id3v2
buf_reader.go
readTillDelims
func (br *bufReader) readTillDelims(delims []byte) ([]byte, error) { if len(delims) == 0 { return nil, nil } if len(delims) == 1 { return br.readTillDelim(delims[0]) } result := make([]byte, 0) for { read, err := br.readTillDelim(delims[0]) if err != nil { return result, err } result = append(result, read...) peeked, err := br.buf.Peek(len(delims)) if err != nil { return result, err } if bytes.Equal(peeked, delims) { break } b, err := br.buf.ReadByte() if err != nil { return result, err } result = append(result, b) } return result, nil }
go
func (br *bufReader) readTillDelims(delims []byte) ([]byte, error) { if len(delims) == 0 { return nil, nil } if len(delims) == 1 { return br.readTillDelim(delims[0]) } result := make([]byte, 0) for { read, err := br.readTillDelim(delims[0]) if err != nil { return result, err } result = append(result, read...) peeked, err := br.buf.Peek(len(delims)) if err != nil { return result, err } if bytes.Equal(peeked, delims) { break } b, err := br.buf.ReadByte() if err != nil { return result, err } result = append(result, b) } return result, nil }
[ "func", "(", "br", "*", "bufReader", ")", "readTillDelims", "(", "delims", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "delims", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if"...
// readTillDelims reads until the first occurrence of delims in the input, // returning a slice containing the data up to and NOT including the delimiters. // If ReadTillDelims encounters an error before finding a delimiters, // it returns the data read before the error and the error itself. // ReadTillDelims returns err != nil if and only if ReadTillDelims didn't find // delims.
[ "readTillDelims", "reads", "until", "the", "first", "occurrence", "of", "delims", "in", "the", "input", "returning", "a", "slice", "containing", "the", "data", "up", "to", "and", "NOT", "including", "the", "delimiters", ".", "If", "ReadTillDelims", "encounters",...
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/buf_reader.go#L124-L158
1,925
bogem/id3v2
buf_reader.go
ReadText
func (br *bufReader) ReadText(encoding Encoding) []byte { if br.err != nil { return nil } var text []byte delims := encoding.TerminationBytes text, br.err = br.readTillDelims(delims) br.Discard(len(delims)) return text }
go
func (br *bufReader) ReadText(encoding Encoding) []byte { if br.err != nil { return nil } var text []byte delims := encoding.TerminationBytes text, br.err = br.readTillDelims(delims) br.Discard(len(delims)) return text }
[ "func", "(", "br", "*", "bufReader", ")", "ReadText", "(", "encoding", "Encoding", ")", "[", "]", "byte", "{", "if", "br", ".", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "var", "text", "[", "]", "byte", "\n", "delims", ":=", "e...
// ReadText reads until the first occurrence of delims in the input, // returning a slice containing the data up to and NOT including the delimiters. // But it discards then termination bytes according to provided encoding.
[ "ReadText", "reads", "until", "the", "first", "occurrence", "of", "delims", "in", "the", "input", "returning", "a", "slice", "containing", "the", "data", "up", "to", "and", "NOT", "including", "the", "delimiters", ".", "But", "it", "discards", "then", "termi...
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/buf_reader.go#L163-L174
1,926
bogem/id3v2
tag.go
AddAttachedPicture
func (tag *Tag) AddAttachedPicture(pf PictureFrame) { tag.AddFrame(tag.CommonID("Attached picture"), pf) }
go
func (tag *Tag) AddAttachedPicture(pf PictureFrame) { tag.AddFrame(tag.CommonID("Attached picture"), pf) }
[ "func", "(", "tag", "*", "Tag", ")", "AddAttachedPicture", "(", "pf", "PictureFrame", ")", "{", "tag", ".", "AddFrame", "(", "tag", ".", "CommonID", "(", "\"", "\"", ")", ",", "pf", ")", "\n", "}" ]
// AddAttachedPicture adds the picture frame to tag.
[ "AddAttachedPicture", "adds", "the", "picture", "frame", "to", "tag", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L50-L52
1,927
bogem/id3v2
tag.go
AddCommentFrame
func (tag *Tag) AddCommentFrame(cf CommentFrame) { tag.AddFrame(tag.CommonID("Comments"), cf) }
go
func (tag *Tag) AddCommentFrame(cf CommentFrame) { tag.AddFrame(tag.CommonID("Comments"), cf) }
[ "func", "(", "tag", "*", "Tag", ")", "AddCommentFrame", "(", "cf", "CommentFrame", ")", "{", "tag", ".", "AddFrame", "(", "tag", ".", "CommonID", "(", "\"", "\"", ")", ",", "cf", ")", "\n", "}" ]
// AddCommentFrame adds the comment frame to tag.
[ "AddCommentFrame", "adds", "the", "comment", "frame", "to", "tag", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L55-L57
1,928
bogem/id3v2
tag.go
AddTextFrame
func (tag *Tag) AddTextFrame(id string, encoding Encoding, text string) { tag.AddFrame(id, TextFrame{Encoding: encoding, Text: text}) }
go
func (tag *Tag) AddTextFrame(id string, encoding Encoding, text string) { tag.AddFrame(id, TextFrame{Encoding: encoding, Text: text}) }
[ "func", "(", "tag", "*", "Tag", ")", "AddTextFrame", "(", "id", "string", ",", "encoding", "Encoding", ",", "text", "string", ")", "{", "tag", ".", "AddFrame", "(", "id", ",", "TextFrame", "{", "Encoding", ":", "encoding", ",", "Text", ":", "text", "...
// AddTextFrame creates the text frame with provided encoding and text // and adds to tag.
[ "AddTextFrame", "creates", "the", "text", "frame", "with", "provided", "encoding", "and", "text", "and", "adds", "to", "tag", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L61-L63
1,929
bogem/id3v2
tag.go
AllFrames
func (tag *Tag) AllFrames() map[string][]Framer { frames := make(map[string][]Framer) for id, f := range tag.frames { frames[id] = []Framer{f} } for id, sequence := range tag.sequences { frames[id] = sequence.Frames() } return frames }
go
func (tag *Tag) AllFrames() map[string][]Framer { frames := make(map[string][]Framer) for id, f := range tag.frames { frames[id] = []Framer{f} } for id, sequence := range tag.sequences { frames[id] = sequence.Frames() } return frames }
[ "func", "(", "tag", "*", "Tag", ")", "AllFrames", "(", ")", "map", "[", "string", "]", "[", "]", "Framer", "{", "frames", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "Framer", ")", "\n\n", "for", "id", ",", "f", ":=", "range", "tag"...
// AllFrames returns map, that contains all frames in tag, that could be parsed. // The key of this map is an ID of frame and value is an array of frames.
[ "AllFrames", "returns", "map", "that", "contains", "all", "frames", "in", "tag", "that", "could", "be", "parsed", ".", "The", "key", "of", "this", "map", "is", "an", "ID", "of", "frame", "and", "value", "is", "an", "array", "of", "frames", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L104-L115
1,930
bogem/id3v2
tag.go
DeleteAllFrames
func (tag *Tag) DeleteAllFrames() { if tag.frames == nil || len(tag.frames) > 0 { tag.frames = make(map[string]Framer) } if tag.sequences == nil || len(tag.sequences) > 0 { for _, s := range tag.sequences { putSequence(s) } tag.sequences = make(map[string]*sequence) } }
go
func (tag *Tag) DeleteAllFrames() { if tag.frames == nil || len(tag.frames) > 0 { tag.frames = make(map[string]Framer) } if tag.sequences == nil || len(tag.sequences) > 0 { for _, s := range tag.sequences { putSequence(s) } tag.sequences = make(map[string]*sequence) } }
[ "func", "(", "tag", "*", "Tag", ")", "DeleteAllFrames", "(", ")", "{", "if", "tag", ".", "frames", "==", "nil", "||", "len", "(", "tag", ".", "frames", ")", ">", "0", "{", "tag", ".", "frames", "=", "make", "(", "map", "[", "string", "]", "Fram...
// DeleteAllFrames deletes all frames in tag.
[ "DeleteAllFrames", "deletes", "all", "frames", "in", "tag", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L118-L128
1,931
bogem/id3v2
tag.go
DeleteFrames
func (tag *Tag) DeleteFrames(id string) { delete(tag.frames, id) if s, ok := tag.sequences[id]; ok { putSequence(s) delete(tag.sequences, id) } }
go
func (tag *Tag) DeleteFrames(id string) { delete(tag.frames, id) if s, ok := tag.sequences[id]; ok { putSequence(s) delete(tag.sequences, id) } }
[ "func", "(", "tag", "*", "Tag", ")", "DeleteFrames", "(", "id", "string", ")", "{", "delete", "(", "tag", ".", "frames", ",", "id", ")", "\n", "if", "s", ",", "ok", ":=", "tag", ".", "sequences", "[", "id", "]", ";", "ok", "{", "putSequence", "...
// DeleteFrames deletes frames in tag with given id.
[ "DeleteFrames", "deletes", "frames", "in", "tag", "with", "given", "id", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L131-L137
1,932
bogem/id3v2
tag.go
Reset
func (tag *Tag) Reset(rd io.Reader, opts Options) error { tag.DeleteAllFrames() return tag.parse(rd, opts) }
go
func (tag *Tag) Reset(rd io.Reader, opts Options) error { tag.DeleteAllFrames() return tag.parse(rd, opts) }
[ "func", "(", "tag", "*", "Tag", ")", "Reset", "(", "rd", "io", ".", "Reader", ",", "opts", "Options", ")", "error", "{", "tag", ".", "DeleteAllFrames", "(", ")", "\n", "return", "tag", ".", "parse", "(", "rd", ",", "opts", ")", "\n", "}" ]
// Reset deletes all frames in tag and parses rd considering opts.
[ "Reset", "deletes", "all", "frames", "in", "tag", "and", "parses", "rd", "considering", "opts", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L140-L143
1,933
bogem/id3v2
tag.go
GetFrames
func (tag *Tag) GetFrames(id string) []Framer { if f, exists := tag.frames[id]; exists { return []Framer{f} } else if s, exists := tag.sequences[id]; exists { return s.Frames() } return nil }
go
func (tag *Tag) GetFrames(id string) []Framer { if f, exists := tag.frames[id]; exists { return []Framer{f} } else if s, exists := tag.sequences[id]; exists { return s.Frames() } return nil }
[ "func", "(", "tag", "*", "Tag", ")", "GetFrames", "(", "id", "string", ")", "[", "]", "Framer", "{", "if", "f", ",", "exists", ":=", "tag", ".", "frames", "[", "id", "]", ";", "exists", "{", "return", "[", "]", "Framer", "{", "f", "}", "\n", ...
// GetFrames returns frames with corresponding id. // It returns nil if there is no frames with given id.
[ "GetFrames", "returns", "frames", "with", "corresponding", "id", ".", "It", "returns", "nil", "if", "there", "is", "no", "frames", "with", "given", "id", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L147-L154
1,934
bogem/id3v2
tag.go
GetLastFrame
func (tag *Tag) GetLastFrame(id string) Framer { // Avoid an allocation of slice in GetFrames, // if there is anyway one frame. if f, exists := tag.frames[id]; exists { return f } fs := tag.GetFrames(id) if len(fs) == 0 { return nil } return fs[len(fs)-1] }
go
func (tag *Tag) GetLastFrame(id string) Framer { // Avoid an allocation of slice in GetFrames, // if there is anyway one frame. if f, exists := tag.frames[id]; exists { return f } fs := tag.GetFrames(id) if len(fs) == 0 { return nil } return fs[len(fs)-1] }
[ "func", "(", "tag", "*", "Tag", ")", "GetLastFrame", "(", "id", "string", ")", "Framer", "{", "// Avoid an allocation of slice in GetFrames,", "// if there is anyway one frame.", "if", "f", ",", "exists", ":=", "tag", ".", "frames", "[", "id", "]", ";", "exists"...
// GetLastFrame returns last frame from slice, that is returned from GetFrames function. // GetLastFrame is suitable for frames, that can be only one in whole tag. // For example, for text frames.
[ "GetLastFrame", "returns", "last", "frame", "from", "slice", "that", "is", "returned", "from", "GetFrames", "function", ".", "GetLastFrame", "is", "suitable", "for", "frames", "that", "can", "be", "only", "one", "in", "whole", "tag", ".", "For", "example", "...
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L159-L171
1,935
bogem/id3v2
tag.go
GetTextFrame
func (tag *Tag) GetTextFrame(id string) TextFrame { f := tag.GetLastFrame(id) if f == nil { return TextFrame{} } tf := f.(TextFrame) return tf }
go
func (tag *Tag) GetTextFrame(id string) TextFrame { f := tag.GetLastFrame(id) if f == nil { return TextFrame{} } tf := f.(TextFrame) return tf }
[ "func", "(", "tag", "*", "Tag", ")", "GetTextFrame", "(", "id", "string", ")", "TextFrame", "{", "f", ":=", "tag", ".", "GetLastFrame", "(", "id", ")", "\n", "if", "f", "==", "nil", "{", "return", "TextFrame", "{", "}", "\n", "}", "\n", "tf", ":=...
// GetTextFrame returns text frame with corresponding id.
[ "GetTextFrame", "returns", "text", "frame", "with", "corresponding", "id", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L174-L181
1,936
bogem/id3v2
tag.go
Count
func (tag *Tag) Count() int { n := len(tag.frames) for _, s := range tag.sequences { n += s.Count() } return n }
go
func (tag *Tag) Count() int { n := len(tag.frames) for _, s := range tag.sequences { n += s.Count() } return n }
[ "func", "(", "tag", "*", "Tag", ")", "Count", "(", ")", "int", "{", "n", ":=", "len", "(", "tag", ".", "frames", ")", "\n", "for", "_", ",", "s", ":=", "range", "tag", ".", "sequences", "{", "n", "+=", "s", ".", "Count", "(", ")", "\n", "}"...
// Count returns the number of frames in tag.
[ "Count", "returns", "the", "number", "of", "frames", "in", "tag", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L206-L212
1,937
bogem/id3v2
tag.go
SetVersion
func (tag *Tag) SetVersion(version byte) { if version < 3 || version > 4 { return } tag.version = version tag.setDefaultEncodingBasedOnVersion(version) }
go
func (tag *Tag) SetVersion(version byte) { if version < 3 || version > 4 { return } tag.version = version tag.setDefaultEncodingBasedOnVersion(version) }
[ "func", "(", "tag", "*", "Tag", ")", "SetVersion", "(", "version", "byte", ")", "{", "if", "version", "<", "3", "||", "version", ">", "4", "{", "return", "\n", "}", "\n", "tag", ".", "version", "=", "version", "\n", "tag", ".", "setDefaultEncodingBas...
// SetVersion sets given ID3v2 version to tag. // If version is less than 3 or greater than 4, then this method will do nothing. // If tag has some frames, which are deprecated or changed in given version, // then to your notice you can delete, change or just stay them.
[ "SetVersion", "sets", "given", "ID3v2", "version", "to", "tag", ".", "If", "version", "is", "less", "than", "3", "or", "greater", "than", "4", "then", "this", "method", "will", "do", "nothing", ".", "If", "tag", "has", "some", "frames", "which", "are", ...
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L304-L310
1,938
bogem/id3v2
tag.go
Save
func (tag *Tag) Save() error { file, ok := tag.reader.(*os.File) if !ok { return ErrNoFile } // Get original file mode. originalFile := file originalStat, err := originalFile.Stat() if err != nil { return err } // Create a temp file for mp3 file, which will contain new tag. name := file.Name() + "-id3v2" newFile, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, originalStat.Mode()) if err != nil { return err } // Make sure we clean up the temp file if it's still around. // tempfileShouldBeRemoved created only for performance // improvement to prevent calling redundant Remove syscalls if file is moved // and is not need to be removed. tempfileShouldBeRemoved := true defer func() { if tempfileShouldBeRemoved { os.Remove(newFile.Name()) } }() // Write tag in new file. tagSize, err := tag.WriteTo(newFile) if err != nil { return err } // Seek to a music part of original file. if _, err = originalFile.Seek(tag.originalSize, os.SEEK_SET); err != nil { return err } // Write to new file the music part. buf := getByteSlice(128 * 1024) defer putByteSlice(buf) if _, err = io.CopyBuffer(newFile, originalFile, buf); err != nil { return err } // Close files to allow replacing. newFile.Close() originalFile.Close() // Replace original file with new file. if err = os.Rename(newFile.Name(), originalFile.Name()); err != nil { return err } tempfileShouldBeRemoved = false // Set tag.reader to new file with original name. tag.reader, err = os.Open(originalFile.Name()) if err != nil { return err } // Set tag.originalSize to new frames size. tag.originalSize = tagSize return nil }
go
func (tag *Tag) Save() error { file, ok := tag.reader.(*os.File) if !ok { return ErrNoFile } // Get original file mode. originalFile := file originalStat, err := originalFile.Stat() if err != nil { return err } // Create a temp file for mp3 file, which will contain new tag. name := file.Name() + "-id3v2" newFile, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, originalStat.Mode()) if err != nil { return err } // Make sure we clean up the temp file if it's still around. // tempfileShouldBeRemoved created only for performance // improvement to prevent calling redundant Remove syscalls if file is moved // and is not need to be removed. tempfileShouldBeRemoved := true defer func() { if tempfileShouldBeRemoved { os.Remove(newFile.Name()) } }() // Write tag in new file. tagSize, err := tag.WriteTo(newFile) if err != nil { return err } // Seek to a music part of original file. if _, err = originalFile.Seek(tag.originalSize, os.SEEK_SET); err != nil { return err } // Write to new file the music part. buf := getByteSlice(128 * 1024) defer putByteSlice(buf) if _, err = io.CopyBuffer(newFile, originalFile, buf); err != nil { return err } // Close files to allow replacing. newFile.Close() originalFile.Close() // Replace original file with new file. if err = os.Rename(newFile.Name(), originalFile.Name()); err != nil { return err } tempfileShouldBeRemoved = false // Set tag.reader to new file with original name. tag.reader, err = os.Open(originalFile.Name()) if err != nil { return err } // Set tag.originalSize to new frames size. tag.originalSize = tagSize return nil }
[ "func", "(", "tag", "*", "Tag", ")", "Save", "(", ")", "error", "{", "file", ",", "ok", ":=", "tag", ".", "reader", ".", "(", "*", "os", ".", "File", ")", "\n", "if", "!", "ok", "{", "return", "ErrNoFile", "\n", "}", "\n\n", "// Get original file...
// Save writes tag to the file, if tag was opened with a file. // If there are no frames in tag, Save will write // only music part without any ID3v2 information. // If tag was initiliazed not with file, it returns ErrNoFile.
[ "Save", "writes", "tag", "to", "the", "file", "if", "tag", "was", "opened", "with", "a", "file", ".", "If", "there", "are", "no", "frames", "in", "tag", "Save", "will", "write", "only", "music", "part", "without", "any", "ID3v2", "information", ".", "I...
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L316-L385
1,939
bogem/id3v2
tag.go
WriteTo
func (tag *Tag) WriteTo(w io.Writer) (n int64, err error) { if w == nil { return 0, errors.New("w is nil") } // Count size of frames. framesSize := tag.Size() - tagHeaderSize if framesSize <= 0 { return 0, nil } // Write tag header. bw := getBufWriter(w) defer putBufWriter(bw) writeTagHeader(bw, uint(framesSize), tag.version) // Write frames. synchSafe := tag.Version() == 4 err = tag.iterateOverAllFrames(func(id string, f Framer) error { return writeFrame(bw, id, f, synchSafe) }) if err != nil { bw.Flush() return bw.Written(), err } return bw.Written(), bw.Flush() }
go
func (tag *Tag) WriteTo(w io.Writer) (n int64, err error) { if w == nil { return 0, errors.New("w is nil") } // Count size of frames. framesSize := tag.Size() - tagHeaderSize if framesSize <= 0 { return 0, nil } // Write tag header. bw := getBufWriter(w) defer putBufWriter(bw) writeTagHeader(bw, uint(framesSize), tag.version) // Write frames. synchSafe := tag.Version() == 4 err = tag.iterateOverAllFrames(func(id string, f Framer) error { return writeFrame(bw, id, f, synchSafe) }) if err != nil { bw.Flush() return bw.Written(), err } return bw.Written(), bw.Flush() }
[ "func", "(", "tag", "*", "Tag", ")", "WriteTo", "(", "w", "io", ".", "Writer", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "if", "w", "==", "nil", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\...
// WriteTo writes whole tag in w if there is at least one frame. // It returns the number of bytes written and error during the write. // It returns nil as error if the write was successful.
[ "WriteTo", "writes", "whole", "tag", "in", "w", "if", "there", "is", "at", "least", "one", "frame", ".", "It", "returns", "the", "number", "of", "bytes", "written", "and", "error", "during", "the", "write", ".", "It", "returns", "nil", "as", "error", "...
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L390-L417
1,940
bogem/id3v2
tag.go
Close
func (tag *Tag) Close() error { file, ok := tag.reader.(*os.File) if !ok { return ErrNoFile } return file.Close() }
go
func (tag *Tag) Close() error { file, ok := tag.reader.(*os.File) if !ok { return ErrNoFile } return file.Close() }
[ "func", "(", "tag", "*", "Tag", ")", "Close", "(", ")", "error", "{", "file", ",", "ok", ":=", "tag", ".", "reader", ".", "(", "*", "os", ".", "File", ")", "\n", "if", "!", "ok", "{", "return", "ErrNoFile", "\n", "}", "\n", "return", "file", ...
// Close closes tag's file, if tag was opened with a file. // If tag was initiliazed not with file, it returns ErrNoFile.
[ "Close", "closes", "tag", "s", "file", "if", "tag", "was", "opened", "with", "a", "file", ".", "If", "tag", "was", "initiliazed", "not", "with", "file", "it", "returns", "ErrNoFile", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/tag.go#L441-L447
1,941
bogem/id3v2
encoding.go
encodedSize
func encodedSize(src string, enc Encoding) int { if enc.Equals(EncodingUTF8) { return len(src) } toXEncoding := resolveXEncoding(nil, enc) encoded, _ := toXEncoding.Encoder().String(src) return len(encoded) }
go
func encodedSize(src string, enc Encoding) int { if enc.Equals(EncodingUTF8) { return len(src) } toXEncoding := resolveXEncoding(nil, enc) encoded, _ := toXEncoding.Encoder().String(src) return len(encoded) }
[ "func", "encodedSize", "(", "src", "string", ",", "enc", "Encoding", ")", "int", "{", "if", "enc", ".", "Equals", "(", "EncodingUTF8", ")", "{", "return", "len", "(", "src", ")", "\n", "}", "\n\n", "toXEncoding", ":=", "resolveXEncoding", "(", "nil", "...
// encodedSize counts length of UTF-8 src if it's encoded to enc.
[ "encodedSize", "counts", "length", "of", "UTF", "-", "8", "src", "if", "it", "s", "encoded", "to", "enc", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/encoding.go#L95-L103
1,942
bogem/id3v2
encoding.go
decodeText
func decodeText(src []byte, from Encoding) string { if from.Equals(EncodingUTF8) { return string(src) } fromXEncoding := resolveXEncoding(src, from) result, err := fromXEncoding.Decoder().Bytes(src) if err != nil { return string(src) } return string(result) }
go
func decodeText(src []byte, from Encoding) string { if from.Equals(EncodingUTF8) { return string(src) } fromXEncoding := resolveXEncoding(src, from) result, err := fromXEncoding.Decoder().Bytes(src) if err != nil { return string(src) } return string(result) }
[ "func", "decodeText", "(", "src", "[", "]", "byte", ",", "from", "Encoding", ")", "string", "{", "if", "from", ".", "Equals", "(", "EncodingUTF8", ")", "{", "return", "string", "(", "src", ")", "\n", "}", "\n\n", "fromXEncoding", ":=", "resolveXEncoding"...
// decodeText decodes src from "from" encoding to UTF-8.
[ "decodeText", "decodes", "src", "from", "from", "encoding", "to", "UTF", "-", "8", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/encoding.go#L106-L117
1,943
bogem/id3v2
encoding.go
encodeWriteText
func encodeWriteText(bw *bufWriter, src string, to Encoding) error { if to.Equals(EncodingUTF8) { bw.WriteString(src) return nil } toXEncoding := resolveXEncoding(nil, to) encoded, err := toXEncoding.Encoder().String(src) if err != nil { return err } bw.WriteString(encoded) return nil }
go
func encodeWriteText(bw *bufWriter, src string, to Encoding) error { if to.Equals(EncodingUTF8) { bw.WriteString(src) return nil } toXEncoding := resolveXEncoding(nil, to) encoded, err := toXEncoding.Encoder().String(src) if err != nil { return err } bw.WriteString(encoded) return nil }
[ "func", "encodeWriteText", "(", "bw", "*", "bufWriter", ",", "src", "string", ",", "to", "Encoding", ")", "error", "{", "if", "to", ".", "Equals", "(", "EncodingUTF8", ")", "{", "bw", ".", "WriteString", "(", "src", ")", "\n", "return", "nil", "\n", ...
// encodeWriteText encodes src from UTF-8 to "to" encoding and writes to bw.
[ "encodeWriteText", "encodes", "src", "from", "UTF", "-", "8", "to", "to", "encoding", "and", "writes", "to", "bw", "." ]
a4e250fe50b485ccf31559c7b8983ce7d98dbbb9
https://github.com/bogem/id3v2/blob/a4e250fe50b485ccf31559c7b8983ce7d98dbbb9/encoding.go#L120-L133
1,944
ipfs/go-log
writer/option.go
Output
func Output(w io.Writer) Option { return func() { backend := logging.NewLogBackend(w, "", 0) logging.SetBackend(backend) // TODO return previous Output option } }
go
func Output(w io.Writer) Option { return func() { backend := logging.NewLogBackend(w, "", 0) logging.SetBackend(backend) // TODO return previous Output option } }
[ "func", "Output", "(", "w", "io", ".", "Writer", ")", "Option", "{", "return", "func", "(", ")", "{", "backend", ":=", "logging", ".", "NewLogBackend", "(", "w", ",", "\"", "\"", ",", "0", ")", "\n", "logging", ".", "SetBackend", "(", "backend", ")...
// Output returns an option which sets the the given writer as the new // logging backend
[ "Output", "returns", "an", "option", "which", "sets", "the", "the", "given", "writer", "as", "the", "new", "logging", "backend" ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/writer/option.go#L34-L40
1,945
ipfs/go-log
context.go
ContextWithLoggable
func ContextWithLoggable(ctx context.Context, l Loggable) context.Context { existing, err := MetadataFromContext(ctx) if err != nil { // context does not contain meta. just set the new metadata child := context.WithValue(ctx, metadataKey, Metadata(l.Loggable())) return child } merged := DeepMerge(existing, l.Loggable()) child := context.WithValue(ctx, metadataKey, merged) return child }
go
func ContextWithLoggable(ctx context.Context, l Loggable) context.Context { existing, err := MetadataFromContext(ctx) if err != nil { // context does not contain meta. just set the new metadata child := context.WithValue(ctx, metadataKey, Metadata(l.Loggable())) return child } merged := DeepMerge(existing, l.Loggable()) child := context.WithValue(ctx, metadataKey, merged) return child }
[ "func", "ContextWithLoggable", "(", "ctx", "context", ".", "Context", ",", "l", "Loggable", ")", "context", ".", "Context", "{", "existing", ",", "err", ":=", "MetadataFromContext", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "// context does not c...
// ContextWithLoggable returns a derived context which contains the provided // Loggable. Any Events logged with the derived context will include the // provided Loggable.
[ "ContextWithLoggable", "returns", "a", "derived", "context", "which", "contains", "the", "provided", "Loggable", ".", "Any", "Events", "logged", "with", "the", "derived", "context", "will", "include", "the", "provided", "Loggable", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/context.go#L15-L26
1,946
ipfs/go-log
context.go
MetadataFromContext
func MetadataFromContext(ctx context.Context) (Metadata, error) { value := ctx.Value(metadataKey) if value != nil { metadata, ok := value.(Metadata) if ok { return metadata, nil } } return nil, errors.New("context contains no metadata") }
go
func MetadataFromContext(ctx context.Context) (Metadata, error) { value := ctx.Value(metadataKey) if value != nil { metadata, ok := value.(Metadata) if ok { return metadata, nil } } return nil, errors.New("context contains no metadata") }
[ "func", "MetadataFromContext", "(", "ctx", "context", ".", "Context", ")", "(", "Metadata", ",", "error", ")", "{", "value", ":=", "ctx", ".", "Value", "(", "metadataKey", ")", "\n", "if", "value", "!=", "nil", "{", "metadata", ",", "ok", ":=", "value"...
// MetadataFromContext extracts Matadata from a given context's value.
[ "MetadataFromContext", "extracts", "Matadata", "from", "a", "given", "context", "s", "value", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/context.go#L29-L38
1,947
ipfs/go-log
log.go
Logger
func Logger(system string) EventLogger { // TODO if we would like to adjust log levels at run-time. Store this event // logger in a map (just like the util.Logger impl) if len(system) == 0 { setuplog := getLogger("setup-logger") setuplog.Warning("Missing name parameter") system = "undefined" } logger := getLogger(system) return &eventLogger{system: system, StandardLogger: logger} }
go
func Logger(system string) EventLogger { // TODO if we would like to adjust log levels at run-time. Store this event // logger in a map (just like the util.Logger impl) if len(system) == 0 { setuplog := getLogger("setup-logger") setuplog.Warning("Missing name parameter") system = "undefined" } logger := getLogger(system) return &eventLogger{system: system, StandardLogger: logger} }
[ "func", "Logger", "(", "system", "string", ")", "EventLogger", "{", "// TODO if we would like to adjust log levels at run-time. Store this event", "// logger in a map (just like the util.Logger impl)", "if", "len", "(", "system", ")", "==", "0", "{", "setuplog", ":=", "getLog...
// Logger retrieves an event logger by name
[ "Logger", "retrieves", "an", "event", "logger", "by", "name" ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/log.go#L147-L160
1,948
ipfs/go-log
log.go
Append
func (eip *EventInProgress) Append(l Loggable) { eip.loggables = append(eip.loggables, l) }
go
func (eip *EventInProgress) Append(l Loggable) { eip.loggables = append(eip.loggables, l) }
[ "func", "(", "eip", "*", "EventInProgress", ")", "Append", "(", "l", "Loggable", ")", "{", "eip", ".", "loggables", "=", "append", "(", "eip", ".", "loggables", ",", "l", ")", "\n", "}" ]
// DEPRECATED use `LogKV` or `SetTag` // Append adds loggables to be included in the call to Done
[ "DEPRECATED", "use", "LogKV", "or", "SetTag", "Append", "adds", "loggables", "to", "be", "included", "in", "the", "call", "to", "Done" ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/log.go#L364-L366
1,949
ipfs/go-log
log.go
FormatRFC3339
func FormatRFC3339(t time.Time) string { return t.UTC().Format(time.RFC3339Nano) }
go
func FormatRFC3339(t time.Time) string { return t.UTC().Format(time.RFC3339Nano) }
[ "func", "FormatRFC3339", "(", "t", "time", ".", "Time", ")", "string", "{", "return", "t", ".", "UTC", "(", ")", ".", "Format", "(", "time", ".", "RFC3339Nano", ")", "\n", "}" ]
// FormatRFC3339 returns the given time in UTC with RFC3999Nano format.
[ "FormatRFC3339", "returns", "the", "given", "time", "in", "UTC", "with", "RFC3999Nano", "format", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/log.go#L402-L404
1,950
ipfs/go-log
oldlog.go
SetAllLoggers
func SetAllLoggers(lvl logging.Level) { logging.SetLevel(lvl, "") loggerMutex.RLock() defer loggerMutex.RUnlock() for n := range loggers { logging.SetLevel(lvl, n) } }
go
func SetAllLoggers(lvl logging.Level) { logging.SetLevel(lvl, "") loggerMutex.RLock() defer loggerMutex.RUnlock() for n := range loggers { logging.SetLevel(lvl, n) } }
[ "func", "SetAllLoggers", "(", "lvl", "logging", ".", "Level", ")", "{", "logging", ".", "SetLevel", "(", "lvl", ",", "\"", "\"", ")", "\n\n", "loggerMutex", ".", "RLock", "(", ")", "\n", "defer", "loggerMutex", ".", "RUnlock", "(", ")", "\n\n", "for", ...
// SetAllLoggers changes the logging.Level of all loggers to lvl
[ "SetAllLoggers", "changes", "the", "logging", ".", "Level", "of", "all", "loggers", "to", "lvl" ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/oldlog.go#L115-L124
1,951
ipfs/go-log
oldlog.go
GetSubsystems
func GetSubsystems() []string { loggerMutex.RLock() defer loggerMutex.RUnlock() subs := make([]string, 0, len(loggers)) for k := range loggers { subs = append(subs, k) } return subs }
go
func GetSubsystems() []string { loggerMutex.RLock() defer loggerMutex.RUnlock() subs := make([]string, 0, len(loggers)) for k := range loggers { subs = append(subs, k) } return subs }
[ "func", "GetSubsystems", "(", ")", "[", "]", "string", "{", "loggerMutex", ".", "RLock", "(", ")", "\n", "defer", "loggerMutex", ".", "RUnlock", "(", ")", "\n", "subs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "loggers", ")...
// GetSubsystems returns a slice containing the // names of the current loggers
[ "GetSubsystems", "returns", "a", "slice", "containing", "the", "names", "of", "the", "current", "loggers" ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/oldlog.go#L155-L164
1,952
ipfs/go-log
writer/polite_json_formatter.go
Format
func (f *PoliteJSONFormatter) Format(calldepth int, r *logging.Record, w io.Writer) error { entry := make(map[string]interface{}) entry["id"] = r.Id entry["level"] = r.Level entry["time"] = r.Time entry["module"] = r.Module entry["message"] = r.Message() err := json.NewEncoder(w).Encode(entry) if err != nil { return err } w.Write([]byte{'\n'}) return nil }
go
func (f *PoliteJSONFormatter) Format(calldepth int, r *logging.Record, w io.Writer) error { entry := make(map[string]interface{}) entry["id"] = r.Id entry["level"] = r.Level entry["time"] = r.Time entry["module"] = r.Module entry["message"] = r.Message() err := json.NewEncoder(w).Encode(entry) if err != nil { return err } w.Write([]byte{'\n'}) return nil }
[ "func", "(", "f", "*", "PoliteJSONFormatter", ")", "Format", "(", "calldepth", "int", ",", "r", "*", "logging", ".", "Record", ",", "w", "io", ".", "Writer", ")", "error", "{", "entry", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", ...
// Format encodes a logging.Record in JSON and writes it to Writer.
[ "Format", "encodes", "a", "logging", ".", "Record", "in", "JSON", "and", "writes", "it", "to", "Writer", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/writer/polite_json_formatter.go#L15-L29
1,953
ipfs/go-log
writer/writer.go
NewMirrorWriter
func NewMirrorWriter() *MirrorWriter { mw := &MirrorWriter{ msgSync: make(chan []byte, 64), // sufficiently large buffer to avoid callers waiting writerAdd: make(chan *writerAdd), } go mw.logRoutine() return mw }
go
func NewMirrorWriter() *MirrorWriter { mw := &MirrorWriter{ msgSync: make(chan []byte, 64), // sufficiently large buffer to avoid callers waiting writerAdd: make(chan *writerAdd), } go mw.logRoutine() return mw }
[ "func", "NewMirrorWriter", "(", ")", "*", "MirrorWriter", "{", "mw", ":=", "&", "MirrorWriter", "{", "msgSync", ":", "make", "(", "chan", "[", "]", "byte", ",", "64", ")", ",", "// sufficiently large buffer to avoid callers waiting", "writerAdd", ":", "make", ...
// NewMirrorWriter initializes and returns a MirrorWriter.
[ "NewMirrorWriter", "initializes", "and", "returns", "a", "MirrorWriter", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/writer/writer.go#L35-L44
1,954
ipfs/go-log
writer/writer.go
Write
func (mw *MirrorWriter) Write(b []byte) (int, error) { mycopy := make([]byte, len(b)) copy(mycopy, b) mw.msgSync <- mycopy return len(b), nil }
go
func (mw *MirrorWriter) Write(b []byte) (int, error) { mycopy := make([]byte, len(b)) copy(mycopy, b) mw.msgSync <- mycopy return len(b), nil }
[ "func", "(", "mw", "*", "MirrorWriter", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "mycopy", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "b", ")", ")", "\n", "copy", "(", "mycopy", ",", "b", ...
// Write broadcasts the written bytes to all Writers.
[ "Write", "broadcasts", "the", "written", "bytes", "to", "all", "Writers", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/writer/writer.go#L47-L52
1,955
ipfs/go-log
writer/writer.go
broadcastMessage
func (mw *MirrorWriter) broadcastMessage(b []byte) bool { var dropped bool for i, w := range mw.writers { _, err := w.Write(b) if err != nil { mw.writers[i] = nil dropped = true } } return dropped }
go
func (mw *MirrorWriter) broadcastMessage(b []byte) bool { var dropped bool for i, w := range mw.writers { _, err := w.Write(b) if err != nil { mw.writers[i] = nil dropped = true } } return dropped }
[ "func", "(", "mw", "*", "MirrorWriter", ")", "broadcastMessage", "(", "b", "[", "]", "byte", ")", "bool", "{", "var", "dropped", "bool", "\n", "for", "i", ",", "w", ":=", "range", "mw", ".", "writers", "{", "_", ",", "err", ":=", "w", ".", "Write...
// broadcastMessage sends the given message to every writer // if any writer is killed during the send, 'true' is returned
[ "broadcastMessage", "sends", "the", "given", "message", "to", "every", "writer", "if", "any", "writer", "is", "killed", "during", "the", "send", "true", "is", "returned" ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/writer/writer.go#L100-L110
1,956
ipfs/go-log
writer/writer.go
AddWriter
func (mw *MirrorWriter) AddWriter(w io.WriteCloser) { wa := &writerAdd{ w: w, done: make(chan struct{}), } mw.writerAdd <- wa <-wa.done }
go
func (mw *MirrorWriter) AddWriter(w io.WriteCloser) { wa := &writerAdd{ w: w, done: make(chan struct{}), } mw.writerAdd <- wa <-wa.done }
[ "func", "(", "mw", "*", "MirrorWriter", ")", "AddWriter", "(", "w", "io", ".", "WriteCloser", ")", "{", "wa", ":=", "&", "writerAdd", "{", "w", ":", "w", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "mw", ".",...
// AddWriter attaches a new WriteCloser to this MirrorWriter. // The new writer will start getting any bytes written to the mirror.
[ "AddWriter", "attaches", "a", "new", "WriteCloser", "to", "this", "MirrorWriter", ".", "The", "new", "writer", "will", "start", "getting", "any", "bytes", "written", "to", "the", "mirror", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/writer/writer.go#L132-L139
1,957
ipfs/go-log
loggable.go
Deferred
func Deferred(key string, f func() string) Loggable { function := func() map[string]interface{} { return map[string]interface{}{ key: f(), } } return LoggableF(function) }
go
func Deferred(key string, f func() string) Loggable { function := func() map[string]interface{} { return map[string]interface{}{ key: f(), } } return LoggableF(function) }
[ "func", "Deferred", "(", "key", "string", ",", "f", "func", "(", ")", "string", ")", "Loggable", "{", "function", ":=", "func", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "return", "map", "[", "string", "]", "interface", "{", ...
// Deferred returns a LoggableF where the execution of the // provided function is deferred.
[ "Deferred", "returns", "a", "LoggableF", "where", "the", "execution", "of", "the", "provided", "function", "is", "deferred", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/loggable.go#L28-L35
1,958
ipfs/go-log
metadata.go
DeepMerge
func DeepMerge(b, a Metadata) Metadata { out := Metadata{} for k, v := range b { out[k] = v } for k, v := range a { maybe, err := Metadatify(v) if err != nil { // if the new value is not meta. just overwrite the dest vaue if out[k] != nil { log.Debugf("Overwriting key: %s, old: %s, new: %s", k, out[k], v) } out[k] = v continue } // it is meta. What about dest? outv, exists := out[k] if !exists { // the new value is meta, but there's no dest value. just write it out[k] = v continue } outMetadataValue, err := Metadatify(outv) if err != nil { // the new value is meta and there's a dest value, but the dest // value isn't meta. just overwrite out[k] = v continue } // both are meta. merge them. out[k] = DeepMerge(outMetadataValue, maybe) } return out }
go
func DeepMerge(b, a Metadata) Metadata { out := Metadata{} for k, v := range b { out[k] = v } for k, v := range a { maybe, err := Metadatify(v) if err != nil { // if the new value is not meta. just overwrite the dest vaue if out[k] != nil { log.Debugf("Overwriting key: %s, old: %s, new: %s", k, out[k], v) } out[k] = v continue } // it is meta. What about dest? outv, exists := out[k] if !exists { // the new value is meta, but there's no dest value. just write it out[k] = v continue } outMetadataValue, err := Metadatify(outv) if err != nil { // the new value is meta and there's a dest value, but the dest // value isn't meta. just overwrite out[k] = v continue } // both are meta. merge them. out[k] = DeepMerge(outMetadataValue, maybe) } return out }
[ "func", "DeepMerge", "(", "b", ",", "a", "Metadata", ")", "Metadata", "{", "out", ":=", "Metadata", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "b", "{", "out", "[", "k", "]", "=", "v", "\n", "}", "\n", "for", "k", ",", "v", ":=", ...
// DeepMerge merges the second Metadata parameter into the first. // Nested Metadata are merged recursively. Primitives are over-written.
[ "DeepMerge", "merges", "the", "second", "Metadata", "parameter", "into", "the", "first", ".", "Nested", "Metadata", "are", "merged", "recursively", ".", "Primitives", "are", "over", "-", "written", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/metadata.go#L14-L51
1,959
ipfs/go-log
metadata.go
JsonString
func (m Metadata) JsonString() (string, error) { // NB: method defined on value b, err := json.Marshal(m) return string(b), err }
go
func (m Metadata) JsonString() (string, error) { // NB: method defined on value b, err := json.Marshal(m) return string(b), err }
[ "func", "(", "m", "Metadata", ")", "JsonString", "(", ")", "(", "string", ",", "error", ")", "{", "// NB: method defined on value", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "m", ")", "\n", "return", "string", "(", "b", ")", ",", "err", "\n...
// JsonString returns the marshaled JSON string for the metadata.
[ "JsonString", "returns", "the", "marshaled", "JSON", "string", "for", "the", "metadata", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/metadata.go#L60-L64
1,960
ipfs/go-log
metadata.go
Metadatify
func Metadatify(i interface{}) (Metadata, error) { value := reflect.ValueOf(i) if value.Kind() == reflect.Map { m := map[string]interface{}{} for _, k := range value.MapKeys() { m[k.String()] = value.MapIndex(k).Interface() } return Metadata(m), nil } return nil, errors.New("is not a map") }
go
func Metadatify(i interface{}) (Metadata, error) { value := reflect.ValueOf(i) if value.Kind() == reflect.Map { m := map[string]interface{}{} for _, k := range value.MapKeys() { m[k.String()] = value.MapIndex(k).Interface() } return Metadata(m), nil } return nil, errors.New("is not a map") }
[ "func", "Metadatify", "(", "i", "interface", "{", "}", ")", "(", "Metadata", ",", "error", ")", "{", "value", ":=", "reflect", ".", "ValueOf", "(", "i", ")", "\n", "if", "value", ".", "Kind", "(", ")", "==", "reflect", ".", "Map", "{", "m", ":=",...
// Metadatify converts maps into Metadata.
[ "Metadatify", "converts", "maps", "into", "Metadata", "." ]
91b837264c0f35dd4e2be341d711316b91d3573d
https://github.com/ipfs/go-log/blob/91b837264c0f35dd4e2be341d711316b91d3573d/metadata.go#L67-L77
1,961
koding/multiconfig
file.go
Load
func (t *TOMLLoader) Load(s interface{}) error { var r io.Reader if t.Reader != nil { r = t.Reader } else if t.Path != "" { file, err := getConfig(t.Path) if err != nil { return err } defer file.Close() r = file } else { return ErrSourceNotSet } if _, err := toml.DecodeReader(r, s); err != nil { return err } return nil }
go
func (t *TOMLLoader) Load(s interface{}) error { var r io.Reader if t.Reader != nil { r = t.Reader } else if t.Path != "" { file, err := getConfig(t.Path) if err != nil { return err } defer file.Close() r = file } else { return ErrSourceNotSet } if _, err := toml.DecodeReader(r, s); err != nil { return err } return nil }
[ "func", "(", "t", "*", "TOMLLoader", ")", "Load", "(", "s", "interface", "{", "}", ")", "error", "{", "var", "r", "io", ".", "Reader", "\n\n", "if", "t", ".", "Reader", "!=", "nil", "{", "r", "=", "t", ".", "Reader", "\n", "}", "else", "if", ...
// Load loads the source into the config defined by struct s // Defaults to using the Reader if provided, otherwise tries to read from the // file
[ "Load", "loads", "the", "source", "into", "the", "config", "defined", "by", "struct", "s", "Defaults", "to", "using", "the", "Reader", "if", "provided", "otherwise", "tries", "to", "read", "from", "the", "file" ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/file.go#L33-L54
1,962
koding/multiconfig
flag.go
processField
func (f *FlagLoader) processField(fieldName string, field *structs.Field) error { if f.CamelCase { fieldName = strings.Join(camelcase.Split(fieldName), "-") fieldName = strings.Replace(fieldName, "---", "-", -1) } switch field.Kind() { case reflect.Struct: for _, ff := range field.Fields() { flagName := field.Name() + "-" + ff.Name() if f.Flatten { // first check if it's set or not, because if we have duplicate // we don't want to break the flag. Panic by giving a readable // output f.flagSet.VisitAll(func(fl *flag.Flag) { if strings.ToLower(ff.Name()) == fl.Name { // already defined panic(fmt.Sprintf("flag '%s' is already defined in outer struct", fl.Name)) } }) flagName = ff.Name() } if err := f.processField(flagName, ff); err != nil { return err } } default: // Add custom prefix to the flag if it's set if f.Prefix != "" { fieldName = f.Prefix + "-" + fieldName } // we only can get the value from expored fields, unexported fields panics if field.IsExported() { f.flagSet.Var(newFieldValue(field), flagName(fieldName), f.flagUsage(fieldName, field)) } } return nil }
go
func (f *FlagLoader) processField(fieldName string, field *structs.Field) error { if f.CamelCase { fieldName = strings.Join(camelcase.Split(fieldName), "-") fieldName = strings.Replace(fieldName, "---", "-", -1) } switch field.Kind() { case reflect.Struct: for _, ff := range field.Fields() { flagName := field.Name() + "-" + ff.Name() if f.Flatten { // first check if it's set or not, because if we have duplicate // we don't want to break the flag. Panic by giving a readable // output f.flagSet.VisitAll(func(fl *flag.Flag) { if strings.ToLower(ff.Name()) == fl.Name { // already defined panic(fmt.Sprintf("flag '%s' is already defined in outer struct", fl.Name)) } }) flagName = ff.Name() } if err := f.processField(flagName, ff); err != nil { return err } } default: // Add custom prefix to the flag if it's set if f.Prefix != "" { fieldName = f.Prefix + "-" + fieldName } // we only can get the value from expored fields, unexported fields panics if field.IsExported() { f.flagSet.Var(newFieldValue(field), flagName(fieldName), f.flagUsage(fieldName, field)) } } return nil }
[ "func", "(", "f", "*", "FlagLoader", ")", "processField", "(", "fieldName", "string", ",", "field", "*", "structs", ".", "Field", ")", "error", "{", "if", "f", ".", "CamelCase", "{", "fieldName", "=", "strings", ".", "Join", "(", "camelcase", ".", "Spl...
// processField generates a flag based on the given field and fieldName. If a // nested struct is detected, a flag for each field of that nested struct is // generated too.
[ "processField", "generates", "a", "flag", "based", "on", "the", "given", "field", "and", "fieldName", ".", "If", "a", "nested", "struct", "is", "detected", "a", "flag", "for", "each", "field", "of", "that", "nested", "struct", "is", "generated", "too", "."...
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/flag.go#L109-L151
1,963
koding/multiconfig
multiloader.go
MustLoad
func (m multiLoader) MustLoad(s interface{}) { if err := m.Load(s); err != nil { panic(err) } }
go
func (m multiLoader) MustLoad(s interface{}) { if err := m.Load(s); err != nil { panic(err) } }
[ "func", "(", "m", "multiLoader", ")", "MustLoad", "(", "s", "interface", "{", "}", ")", "{", "if", "err", ":=", "m", ".", "Load", "(", "s", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// MustLoad loads the source into the struct, it panics if gets any error
[ "MustLoad", "loads", "the", "source", "into", "the", "struct", "it", "panics", "if", "gets", "any", "error" ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/multiloader.go#L23-L27
1,964
koding/multiconfig
env.go
processField
func (e *EnvironmentLoader) processField(prefix string, field *structs.Field, name string, strctMap interface{}) error { fieldName := e.generateFieldName(prefix, name) switch strctMap.(type) { case map[string]interface{}: for key, val := range strctMap.(map[string]interface{}) { field := field.Field(key) if err := e.processField(fieldName, field, key, val); err != nil { return err } } default: v := os.Getenv(fieldName) if v == "" { return nil } if err := fieldSet(field, v); err != nil { return err } } return nil }
go
func (e *EnvironmentLoader) processField(prefix string, field *structs.Field, name string, strctMap interface{}) error { fieldName := e.generateFieldName(prefix, name) switch strctMap.(type) { case map[string]interface{}: for key, val := range strctMap.(map[string]interface{}) { field := field.Field(key) if err := e.processField(fieldName, field, key, val); err != nil { return err } } default: v := os.Getenv(fieldName) if v == "" { return nil } if err := fieldSet(field, v); err != nil { return err } } return nil }
[ "func", "(", "e", "*", "EnvironmentLoader", ")", "processField", "(", "prefix", "string", ",", "field", "*", "structs", ".", "Field", ",", "name", "string", ",", "strctMap", "interface", "{", "}", ")", "error", "{", "fieldName", ":=", "e", ".", "generate...
// processField gets leading name for the env variable and combines the current // field's name and generates environment variable names recursively
[ "processField", "gets", "leading", "name", "for", "the", "env", "variable", "and", "combines", "the", "current", "field", "s", "name", "and", "generates", "environment", "variable", "names", "recursively" ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/env.go#L55-L79
1,965
koding/multiconfig
env.go
PrintEnvs
func (e *EnvironmentLoader) PrintEnvs(s interface{}) { strct := structs.New(s) strctMap := strct.Map() prefix := e.getPrefix(strct) keys := make([]string, 0, len(strctMap)) for key := range strctMap { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { field := strct.Field(key) e.printField(prefix, field, key, strctMap[key]) } }
go
func (e *EnvironmentLoader) PrintEnvs(s interface{}) { strct := structs.New(s) strctMap := strct.Map() prefix := e.getPrefix(strct) keys := make([]string, 0, len(strctMap)) for key := range strctMap { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { field := strct.Field(key) e.printField(prefix, field, key, strctMap[key]) } }
[ "func", "(", "e", "*", "EnvironmentLoader", ")", "PrintEnvs", "(", "s", "interface", "{", "}", ")", "{", "strct", ":=", "structs", ".", "New", "(", "s", ")", "\n", "strctMap", ":=", "strct", ".", "Map", "(", ")", "\n", "prefix", ":=", "e", ".", "...
// PrintEnvs prints the generated environment variables to the std out.
[ "PrintEnvs", "prints", "the", "generated", "environment", "variables", "to", "the", "std", "out", "." ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/env.go#L82-L97
1,966
koding/multiconfig
env.go
printField
func (e *EnvironmentLoader) printField(prefix string, field *structs.Field, name string, strctMap interface{}) { fieldName := e.generateFieldName(prefix, name) switch strctMap.(type) { case map[string]interface{}: smap := strctMap.(map[string]interface{}) keys := make([]string, 0, len(smap)) for key := range smap { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { field := field.Field(key) e.printField(fieldName, field, key, smap[key]) } default: fmt.Println(" ", fieldName) } }
go
func (e *EnvironmentLoader) printField(prefix string, field *structs.Field, name string, strctMap interface{}) { fieldName := e.generateFieldName(prefix, name) switch strctMap.(type) { case map[string]interface{}: smap := strctMap.(map[string]interface{}) keys := make([]string, 0, len(smap)) for key := range smap { keys = append(keys, key) } sort.Strings(keys) for _, key := range keys { field := field.Field(key) e.printField(fieldName, field, key, smap[key]) } default: fmt.Println(" ", fieldName) } }
[ "func", "(", "e", "*", "EnvironmentLoader", ")", "printField", "(", "prefix", "string", ",", "field", "*", "structs", ".", "Field", ",", "name", "string", ",", "strctMap", "interface", "{", "}", ")", "{", "fieldName", ":=", "e", ".", "generateFieldName", ...
// printField prints the field of the config struct for the flag.Usage
[ "printField", "prints", "the", "field", "of", "the", "config", "struct", "for", "the", "flag", ".", "Usage" ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/env.go#L100-L118
1,967
koding/multiconfig
env.go
generateFieldName
func (e *EnvironmentLoader) generateFieldName(prefix string, name string) string { fieldName := strings.ToUpper(name) if e.CamelCase { fieldName = strings.ToUpper(strings.Join(camelcase.Split(name), "_")) } return strings.ToUpper(prefix) + "_" + fieldName }
go
func (e *EnvironmentLoader) generateFieldName(prefix string, name string) string { fieldName := strings.ToUpper(name) if e.CamelCase { fieldName = strings.ToUpper(strings.Join(camelcase.Split(name), "_")) } return strings.ToUpper(prefix) + "_" + fieldName }
[ "func", "(", "e", "*", "EnvironmentLoader", ")", "generateFieldName", "(", "prefix", "string", ",", "name", "string", ")", "string", "{", "fieldName", ":=", "strings", ".", "ToUpper", "(", "name", ")", "\n", "if", "e", ".", "CamelCase", "{", "fieldName", ...
// generateFieldName generates the field name combined with the prefix and the // struct's field name
[ "generateFieldName", "generates", "the", "field", "name", "combined", "with", "the", "prefix", "and", "the", "struct", "s", "field", "name" ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/env.go#L122-L129
1,968
koding/multiconfig
multivalidator.go
Validate
func (d multiValidator) Validate(s interface{}) error { for _, validator := range d { if err := validator.Validate(s); err != nil { return err } } return nil }
go
func (d multiValidator) Validate(s interface{}) error { for _, validator := range d { if err := validator.Validate(s); err != nil { return err } } return nil }
[ "func", "(", "d", "multiValidator", ")", "Validate", "(", "s", "interface", "{", "}", ")", "error", "{", "for", "_", ",", "validator", ":=", "range", "d", "{", "if", "err", ":=", "validator", ".", "Validate", "(", "s", ")", ";", "err", "!=", "nil",...
// Validate tries to validate given struct with all the validators. If it doesn't // have any Validator it will simply skip the validation step. If any of the // given validators return err, it will stop validating and return it.
[ "Validate", "tries", "to", "validate", "given", "struct", "with", "all", "the", "validators", ".", "If", "it", "doesn", "t", "have", "any", "Validator", "it", "will", "simply", "skip", "the", "validation", "step", ".", "If", "any", "of", "the", "given", ...
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/multivalidator.go#L13-L21
1,969
koding/multiconfig
multivalidator.go
MustValidate
func (d multiValidator) MustValidate(s interface{}) { if err := d.Validate(s); err != nil { panic(err) } }
go
func (d multiValidator) MustValidate(s interface{}) { if err := d.Validate(s); err != nil { panic(err) } }
[ "func", "(", "d", "multiValidator", ")", "MustValidate", "(", "s", "interface", "{", "}", ")", "{", "if", "err", ":=", "d", ".", "Validate", "(", "s", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// MustValidate validates the struct, it panics if gets any error
[ "MustValidate", "validates", "the", "struct", "it", "panics", "if", "gets", "any", "error" ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/multivalidator.go#L24-L28
1,970
koding/multiconfig
tag.go
processField
func (t *TagLoader) processField(tagName string, field *structs.Field) error { switch field.Kind() { case reflect.Struct: for _, f := range field.Fields() { if err := t.processField(tagName, f); err != nil { return err } } default: defaultVal := field.Tag(t.DefaultTagName) if defaultVal == "" { return nil } err := fieldSet(field, defaultVal) if err != nil { return err } } return nil }
go
func (t *TagLoader) processField(tagName string, field *structs.Field) error { switch field.Kind() { case reflect.Struct: for _, f := range field.Fields() { if err := t.processField(tagName, f); err != nil { return err } } default: defaultVal := field.Tag(t.DefaultTagName) if defaultVal == "" { return nil } err := fieldSet(field, defaultVal) if err != nil { return err } } return nil }
[ "func", "(", "t", "*", "TagLoader", ")", "processField", "(", "tagName", "string", ",", "field", "*", "structs", ".", "Field", ")", "error", "{", "switch", "field", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Struct", ":", "for", "_", ",", ...
// processField gets tagName and the field, recursively checks if the field has the given // tag, if yes, sets it otherwise ignores
[ "processField", "gets", "tagName", "and", "the", "field", "recursively", "checks", "if", "the", "field", "has", "the", "given", "tag", "if", "yes", "sets", "it", "otherwise", "ignores" ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/tag.go#L39-L60
1,971
koding/multiconfig
multiconfig.go
NewWithPath
func NewWithPath(path string) *DefaultLoader { loaders := []Loader{} // Read default values defined via tag fields "default" loaders = append(loaders, &TagLoader{}) // Choose what while is passed if strings.HasSuffix(path, "toml") { loaders = append(loaders, &TOMLLoader{Path: path}) } if strings.HasSuffix(path, "json") { loaders = append(loaders, &JSONLoader{Path: path}) } if strings.HasSuffix(path, "yml") || strings.HasSuffix(path, "yaml") { loaders = append(loaders, &YAMLLoader{Path: path}) } e := &EnvironmentLoader{} f := &FlagLoader{} loaders = append(loaders, e, f) loader := MultiLoader(loaders...) d := &DefaultLoader{} d.Loader = loader d.Validator = MultiValidator(&RequiredValidator{}) return d }
go
func NewWithPath(path string) *DefaultLoader { loaders := []Loader{} // Read default values defined via tag fields "default" loaders = append(loaders, &TagLoader{}) // Choose what while is passed if strings.HasSuffix(path, "toml") { loaders = append(loaders, &TOMLLoader{Path: path}) } if strings.HasSuffix(path, "json") { loaders = append(loaders, &JSONLoader{Path: path}) } if strings.HasSuffix(path, "yml") || strings.HasSuffix(path, "yaml") { loaders = append(loaders, &YAMLLoader{Path: path}) } e := &EnvironmentLoader{} f := &FlagLoader{} loaders = append(loaders, e, f) loader := MultiLoader(loaders...) d := &DefaultLoader{} d.Loader = loader d.Validator = MultiValidator(&RequiredValidator{}) return d }
[ "func", "NewWithPath", "(", "path", "string", ")", "*", "DefaultLoader", "{", "loaders", ":=", "[", "]", "Loader", "{", "}", "\n\n", "// Read default values defined via tag fields \"default\"", "loaders", "=", "append", "(", "loaders", ",", "&", "TagLoader", "{", ...
// NewWithPath returns a new instance of Loader to read from the given // configuration file.
[ "NewWithPath", "returns", "a", "new", "instance", "of", "Loader", "to", "read", "from", "the", "given", "configuration", "file", "." ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/multiconfig.go#L35-L64
1,972
koding/multiconfig
multiconfig.go
New
func New() *DefaultLoader { loader := MultiLoader( &TagLoader{}, &EnvironmentLoader{}, &FlagLoader{}, ) d := &DefaultLoader{} d.Loader = loader d.Validator = MultiValidator(&RequiredValidator{}) return d }
go
func New() *DefaultLoader { loader := MultiLoader( &TagLoader{}, &EnvironmentLoader{}, &FlagLoader{}, ) d := &DefaultLoader{} d.Loader = loader d.Validator = MultiValidator(&RequiredValidator{}) return d }
[ "func", "New", "(", ")", "*", "DefaultLoader", "{", "loader", ":=", "MultiLoader", "(", "&", "TagLoader", "{", "}", ",", "&", "EnvironmentLoader", "{", "}", ",", "&", "FlagLoader", "{", "}", ",", ")", "\n\n", "d", ":=", "&", "DefaultLoader", "{", "}"...
// New returns a new instance of DefaultLoader without any file loaders.
[ "New", "returns", "a", "new", "instance", "of", "DefaultLoader", "without", "any", "file", "loaders", "." ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/multiconfig.go#L67-L78
1,973
koding/multiconfig
multiconfig.go
MustLoadWithPath
func MustLoadWithPath(path string, conf interface{}) { d := NewWithPath(path) d.MustLoad(conf) }
go
func MustLoadWithPath(path string, conf interface{}) { d := NewWithPath(path) d.MustLoad(conf) }
[ "func", "MustLoadWithPath", "(", "path", "string", ",", "conf", "interface", "{", "}", ")", "{", "d", ":=", "NewWithPath", "(", "path", ")", "\n", "d", ".", "MustLoad", "(", "conf", ")", "\n", "}" ]
// MustLoadWithPath loads with the DefaultLoader settings and from the given // Path. It exits if the config cannot be parsed.
[ "MustLoadWithPath", "loads", "with", "the", "DefaultLoader", "settings", "and", "from", "the", "given", "Path", ".", "It", "exits", "if", "the", "config", "cannot", "be", "parsed", "." ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/multiconfig.go#L82-L85
1,974
koding/multiconfig
multiconfig.go
MustLoad
func (d *DefaultLoader) MustLoad(conf interface{}) { if err := d.Load(conf); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } // we at koding, believe having sane defaults in our system, this is the // reason why we have default validators in DefaultLoader. But do not cause // nil pointer panics if one uses DefaultLoader directly. if d.Validator != nil { d.MustValidate(conf) } }
go
func (d *DefaultLoader) MustLoad(conf interface{}) { if err := d.Load(conf); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } // we at koding, believe having sane defaults in our system, this is the // reason why we have default validators in DefaultLoader. But do not cause // nil pointer panics if one uses DefaultLoader directly. if d.Validator != nil { d.MustValidate(conf) } }
[ "func", "(", "d", "*", "DefaultLoader", ")", "MustLoad", "(", "conf", "interface", "{", "}", ")", "{", "if", "err", ":=", "d", ".", "Load", "(", "conf", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "...
// MustLoad is like Load but panics if the config cannot be parsed.
[ "MustLoad", "is", "like", "Load", "but", "panics", "if", "the", "config", "cannot", "be", "parsed", "." ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/multiconfig.go#L95-L107
1,975
koding/multiconfig
multiconfig.go
MustValidate
func (d *DefaultLoader) MustValidate(conf interface{}) { if err := d.Validate(conf); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } }
go
func (d *DefaultLoader) MustValidate(conf interface{}) { if err := d.Validate(conf); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } }
[ "func", "(", "d", "*", "DefaultLoader", ")", "MustValidate", "(", "conf", "interface", "{", "}", ")", "{", "if", "err", ":=", "d", ".", "Validate", "(", "conf", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ...
// MustValidate validates the struct. It exits with status 1 if it can't // validate.
[ "MustValidate", "validates", "the", "struct", ".", "It", "exits", "with", "status", "1", "if", "it", "can", "t", "validate", "." ]
69c27309b2d751c576b59ea9c3726597c2375da3
https://github.com/koding/multiconfig/blob/69c27309b2d751c576b59ea9c3726597c2375da3/multiconfig.go#L111-L116
1,976
joeshaw/envdecode
envdecode.go
StrictDecode
func StrictDecode(target interface{}) error { nFields, err := decode(target, true) if err != nil { return err } // if we didn't do anything - the user probably did something // wrong like leave all fields unexported. if nFields == 0 { return ErrInvalidTarget } return nil }
go
func StrictDecode(target interface{}) error { nFields, err := decode(target, true) if err != nil { return err } // if we didn't do anything - the user probably did something // wrong like leave all fields unexported. if nFields == 0 { return ErrInvalidTarget } return nil }
[ "func", "StrictDecode", "(", "target", "interface", "{", "}", ")", "error", "{", "nFields", ",", "err", ":=", "decode", "(", "target", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// if we didn't do anything...
// StrictDecode is similar to Decode except all fields will have an implicit // ",strict" on all fields.
[ "StrictDecode", "is", "similar", "to", "Decode", "except", "all", "fields", "will", "have", "an", "implicit", "strict", "on", "all", "fields", "." ]
c9e0158544672841c3ebf49308f536d918f2e525
https://github.com/joeshaw/envdecode/blob/c9e0158544672841c3ebf49308f536d918f2e525/envdecode.go#L77-L90
1,977
advancedlogic/GoOse
crawler.go
GetContentType
func (c Crawler) GetContentType(document *goquery.Document) string { var attr string // <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> document.Find("meta[http-equiv#=(?i)^Content\\-type$]").Each(func(i int, s *goquery.Selection) { attr, _ = s.Attr("content") }) return attr }
go
func (c Crawler) GetContentType(document *goquery.Document) string { var attr string // <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> document.Find("meta[http-equiv#=(?i)^Content\\-type$]").Each(func(i int, s *goquery.Selection) { attr, _ = s.Attr("content") }) return attr }
[ "func", "(", "c", "Crawler", ")", "GetContentType", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "var", "attr", "string", "\n", "// <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />", "document", ".", "Find", "(", "\"",...
// GetContentType returns the Content-Type string extracted from the meta tags
[ "GetContentType", "returns", "the", "Content", "-", "Type", "string", "extracted", "from", "the", "meta", "tags" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/crawler.go#L47-L54
1,978
advancedlogic/GoOse
crawler.go
GetCharset
func (c Crawler) GetCharset(document *goquery.Document) string { // manually-provided charset (from HTTP headers?) takes priority if "" != c.Charset { return c.Charset } // <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ct := c.GetContentType(document) if "" != ct && strings.Contains(strings.ToLower(ct), "charset") { return getCharsetFromContentType(ct) } // <meta charset="utf-8"> selection := document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool { _, exists := s.Attr("charset") return !exists }) if selection != nil { cs, _ := selection.Attr("charset") return NormaliseCharset(cs) } return "" }
go
func (c Crawler) GetCharset(document *goquery.Document) string { // manually-provided charset (from HTTP headers?) takes priority if "" != c.Charset { return c.Charset } // <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ct := c.GetContentType(document) if "" != ct && strings.Contains(strings.ToLower(ct), "charset") { return getCharsetFromContentType(ct) } // <meta charset="utf-8"> selection := document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool { _, exists := s.Attr("charset") return !exists }) if selection != nil { cs, _ := selection.Attr("charset") return NormaliseCharset(cs) } return "" }
[ "func", "(", "c", "Crawler", ")", "GetCharset", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "// manually-provided charset (from HTTP headers?) takes priority", "if", "\"", "\"", "!=", "c", ".", "Charset", "{", "return", "c", ".", "Chars...
// GetCharset returns a normalised charset string extracted from the meta tags
[ "GetCharset", "returns", "a", "normalised", "charset", "string", "extracted", "from", "the", "meta", "tags" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/crawler.go#L57-L81
1,979
advancedlogic/GoOse
crawler.go
Preprocess
func (c *Crawler) Preprocess() (*goquery.Document, error) { var err error if c.RawHTML == "" { if c.RawHTML, err = c.fetchHTML(c.url, c.config.timeout); err != nil { return nil, err } } if c.RawHTML == "" { return nil, errors.New("cannot process empty HTML content") } c.RawHTML = c.addSpacesBetweenTags(c.RawHTML) reader := strings.NewReader(c.RawHTML) document, err := goquery.NewDocumentFromReader(reader) if err != nil { return nil, err } cs := c.GetCharset(document) //log.Println("-------------------------------------------CHARSET:", cs) if "" != cs && "UTF-8" != cs { // the net/html parser and goquery require UTF-8 data c.RawHTML = UTF8encode(c.RawHTML, cs) reader = strings.NewReader(c.RawHTML) if document, err = goquery.NewDocumentFromReader(reader); err != nil { return nil, err } } return document, nil }
go
func (c *Crawler) Preprocess() (*goquery.Document, error) { var err error if c.RawHTML == "" { if c.RawHTML, err = c.fetchHTML(c.url, c.config.timeout); err != nil { return nil, err } } if c.RawHTML == "" { return nil, errors.New("cannot process empty HTML content") } c.RawHTML = c.addSpacesBetweenTags(c.RawHTML) reader := strings.NewReader(c.RawHTML) document, err := goquery.NewDocumentFromReader(reader) if err != nil { return nil, err } cs := c.GetCharset(document) //log.Println("-------------------------------------------CHARSET:", cs) if "" != cs && "UTF-8" != cs { // the net/html parser and goquery require UTF-8 data c.RawHTML = UTF8encode(c.RawHTML, cs) reader = strings.NewReader(c.RawHTML) if document, err = goquery.NewDocumentFromReader(reader); err != nil { return nil, err } } return document, nil }
[ "func", "(", "c", "*", "Crawler", ")", "Preprocess", "(", ")", "(", "*", "goquery", ".", "Document", ",", "error", ")", "{", "var", "err", "error", "\n\n", "if", "c", ".", "RawHTML", "==", "\"", "\"", "{", "if", "c", ".", "RawHTML", ",", "err", ...
// Preprocess fetches the HTML page if needed, converts it to UTF-8 and applies // some text normalisation to guarantee better results when extracting the content
[ "Preprocess", "fetches", "the", "HTML", "page", "if", "needed", "converts", "it", "to", "UTF", "-", "8", "and", "applies", "some", "text", "normalisation", "to", "guarantee", "better", "results", "when", "extracting", "the", "content" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/crawler.go#L85-L117
1,980
advancedlogic/GoOse
crawler.go
Crawl
func (c Crawler) Crawl() (*Article, error) { article := new(Article) document, err := c.Preprocess() if nil != err { return nil, err } if nil == document { return article, nil } extractor := NewExtractor(c.config) startTime := time.Now().UnixNano() article.RawHTML, err = document.Html() if nil != err { return nil, err } article.FinalURL = c.url article.Doc = document article.Title = extractor.GetTitle(document) article.MetaLang = extractor.GetMetaLanguage(document) article.MetaFavicon = extractor.GetFavicon(document) article.MetaDescription = extractor.GetMetaContentWithSelector(document, "meta[name#=(?i)^description$]") article.MetaKeywords = extractor.GetMetaContentWithSelector(document, "meta[name#=(?i)^keywords$]") article.CanonicalLink = extractor.GetCanonicalLink(document) if "" == article.CanonicalLink { article.CanonicalLink = article.FinalURL } article.Domain = extractor.GetDomain(article.CanonicalLink) article.Tags = extractor.GetTags(document) if c.config.extractPublishDate { if timestamp := extractor.GetPublishDate(document); timestamp != nil { article.PublishDate = timestamp } } cleaner := NewCleaner(c.config) article.Doc = cleaner.Clean(article.Doc) article.TopImage = OpenGraphResolver(document) if article.TopImage == "" { article.TopImage = WebPageResolver(article) } article.TopNode = extractor.CalculateBestNode(document) if article.TopNode != nil { article.TopNode = extractor.PostCleanup(article.TopNode) article.CleanedText, article.Links = extractor.GetCleanTextAndLinks(article.TopNode, article.MetaLang) videoExtractor := NewVideoExtractor() article.Movies = videoExtractor.GetVideos(document) } article.Delta = time.Now().UnixNano() - startTime return article, nil }
go
func (c Crawler) Crawl() (*Article, error) { article := new(Article) document, err := c.Preprocess() if nil != err { return nil, err } if nil == document { return article, nil } extractor := NewExtractor(c.config) startTime := time.Now().UnixNano() article.RawHTML, err = document.Html() if nil != err { return nil, err } article.FinalURL = c.url article.Doc = document article.Title = extractor.GetTitle(document) article.MetaLang = extractor.GetMetaLanguage(document) article.MetaFavicon = extractor.GetFavicon(document) article.MetaDescription = extractor.GetMetaContentWithSelector(document, "meta[name#=(?i)^description$]") article.MetaKeywords = extractor.GetMetaContentWithSelector(document, "meta[name#=(?i)^keywords$]") article.CanonicalLink = extractor.GetCanonicalLink(document) if "" == article.CanonicalLink { article.CanonicalLink = article.FinalURL } article.Domain = extractor.GetDomain(article.CanonicalLink) article.Tags = extractor.GetTags(document) if c.config.extractPublishDate { if timestamp := extractor.GetPublishDate(document); timestamp != nil { article.PublishDate = timestamp } } cleaner := NewCleaner(c.config) article.Doc = cleaner.Clean(article.Doc) article.TopImage = OpenGraphResolver(document) if article.TopImage == "" { article.TopImage = WebPageResolver(article) } article.TopNode = extractor.CalculateBestNode(document) if article.TopNode != nil { article.TopNode = extractor.PostCleanup(article.TopNode) article.CleanedText, article.Links = extractor.GetCleanTextAndLinks(article.TopNode, article.MetaLang) videoExtractor := NewVideoExtractor() article.Movies = videoExtractor.GetVideos(document) } article.Delta = time.Now().UnixNano() - startTime return article, nil }
[ "func", "(", "c", "Crawler", ")", "Crawl", "(", ")", "(", "*", "Article", ",", "error", ")", "{", "article", ":=", "new", "(", "Article", ")", "\n\n", "document", ",", "err", ":=", "c", ".", "Preprocess", "(", ")", "\n", "if", "nil", "!=", "err",...
// Crawl fetches the HTML body and returns an Article
[ "Crawl", "fetches", "the", "HTML", "body", "and", "returns", "an", "Article" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/crawler.go#L120-L182
1,981
advancedlogic/GoOse
extractor.go
GetTitle
func (extr *ContentExtractor) GetTitle(document *goquery.Document) string { title := "" titleElement := document.Find("title") if titleElement != nil && titleElement.Size() > 0 { title = titleElement.Text() } if title == "" { ogTitleElement := document.Find(`meta[property="og:title"]`) if ogTitleElement != nil && ogTitleElement.Size() > 0 { title, _ = ogTitleElement.Attr("content") } } if title == "" { titleElement = document.Find("post-title,headline") if titleElement == nil || titleElement.Size() == 0 { return title } title = titleElement.Text() } for _, delimiter := range titleDelimiters { if strings.Contains(title, delimiter) { title = extr.splitTitle(strings.Split(title, delimiter)) break } } title = strings.Replace(title, motleyReplacement, "", -1) if extr.config.debug { log.Printf("Page title is %s\n", title) } return strings.TrimSpace(title) }
go
func (extr *ContentExtractor) GetTitle(document *goquery.Document) string { title := "" titleElement := document.Find("title") if titleElement != nil && titleElement.Size() > 0 { title = titleElement.Text() } if title == "" { ogTitleElement := document.Find(`meta[property="og:title"]`) if ogTitleElement != nil && ogTitleElement.Size() > 0 { title, _ = ogTitleElement.Attr("content") } } if title == "" { titleElement = document.Find("post-title,headline") if titleElement == nil || titleElement.Size() == 0 { return title } title = titleElement.Text() } for _, delimiter := range titleDelimiters { if strings.Contains(title, delimiter) { title = extr.splitTitle(strings.Split(title, delimiter)) break } } title = strings.Replace(title, motleyReplacement, "", -1) if extr.config.debug { log.Printf("Page title is %s\n", title) } return strings.TrimSpace(title) }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetTitle", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "title", ":=", "\"", "\"", "\n\n", "titleElement", ":=", "document", ".", "Find", "(", "\"", "\"", ")", "\n", "if", "ti...
// GetTitle returns the title set in the source, if the article has one
[ "GetTitle", "returns", "the", "title", "set", "in", "the", "source", "if", "the", "article", "has", "one" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L54-L91
1,982
advancedlogic/GoOse
extractor.go
GetMetaLanguage
func (extr *ContentExtractor) GetMetaLanguage(document *goquery.Document) string { var language string shtml := document.Find("html") attr, _ := shtml.Attr("lang") if attr == "" { attr, _ = document.Attr("lang") } if attr == "" { selection := document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool { var exists bool attr, exists = s.Attr("http-equiv") if exists && attr == "content-language" { return false } return true }) if selection != nil { attr, _ = selection.Attr("content") } } idx := strings.LastIndex(attr, "-") if idx == -1 { language = attr } else { language = attr[0:idx] } _, ok := sw[language] if language == "" || !ok { language = extr.config.stopWords.SimpleLanguageDetector(shtml.Text()) if language == "" { language = defaultLanguage } } extr.config.targetLanguage = language return language }
go
func (extr *ContentExtractor) GetMetaLanguage(document *goquery.Document) string { var language string shtml := document.Find("html") attr, _ := shtml.Attr("lang") if attr == "" { attr, _ = document.Attr("lang") } if attr == "" { selection := document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool { var exists bool attr, exists = s.Attr("http-equiv") if exists && attr == "content-language" { return false } return true }) if selection != nil { attr, _ = selection.Attr("content") } } idx := strings.LastIndex(attr, "-") if idx == -1 { language = attr } else { language = attr[0:idx] } _, ok := sw[language] if language == "" || !ok { language = extr.config.stopWords.SimpleLanguageDetector(shtml.Text()) if language == "" { language = defaultLanguage } } extr.config.targetLanguage = language return language }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetMetaLanguage", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "var", "language", "string", "\n", "shtml", ":=", "document", ".", "Find", "(", "\"", "\"", ")", "\n", "attr", ","...
// GetMetaLanguage returns the meta language set in the source, if the article has one
[ "GetMetaLanguage", "returns", "the", "meta", "language", "set", "in", "the", "source", "if", "the", "article", "has", "one" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L108-L146
1,983
advancedlogic/GoOse
extractor.go
GetFavicon
func (extr *ContentExtractor) GetFavicon(document *goquery.Document) string { favicon := "" document.Find("link").EachWithBreak(func(i int, s *goquery.Selection) bool { attr, exists := s.Attr("rel") if exists && strings.Contains(attr, "icon") { favicon, _ = s.Attr("href") return false } return true }) return favicon }
go
func (extr *ContentExtractor) GetFavicon(document *goquery.Document) string { favicon := "" document.Find("link").EachWithBreak(func(i int, s *goquery.Selection) bool { attr, exists := s.Attr("rel") if exists && strings.Contains(attr, "icon") { favicon, _ = s.Attr("href") return false } return true }) return favicon }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetFavicon", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "favicon", ":=", "\"", "\"", "\n", "document", ".", "Find", "(", "\"", "\"", ")", ".", "EachWithBreak", "(", "func", ...
// GetFavicon returns the favicon set in the source, if the article has one
[ "GetFavicon", "returns", "the", "favicon", "set", "in", "the", "source", "if", "the", "article", "has", "one" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L149-L160
1,984
advancedlogic/GoOse
extractor.go
GetMetaContentWithSelector
func (extr *ContentExtractor) GetMetaContentWithSelector(document *goquery.Document, selector string) string { selection := document.Find(selector) content, _ := selection.Attr("content") return strings.TrimSpace(content) }
go
func (extr *ContentExtractor) GetMetaContentWithSelector(document *goquery.Document, selector string) string { selection := document.Find(selector) content, _ := selection.Attr("content") return strings.TrimSpace(content) }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetMetaContentWithSelector", "(", "document", "*", "goquery", ".", "Document", ",", "selector", "string", ")", "string", "{", "selection", ":=", "document", ".", "Find", "(", "selector", ")", "\n", "content",...
// GetMetaContentWithSelector returns the content attribute of meta tag matching the selector
[ "GetMetaContentWithSelector", "returns", "the", "content", "attribute", "of", "meta", "tag", "matching", "the", "selector" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L163-L167
1,985
advancedlogic/GoOse
extractor.go
GetMetaContent
func (extr *ContentExtractor) GetMetaContent(document *goquery.Document, metaName string) string { content := "" document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool { attr, exists := s.Attr("name") if exists && attr == metaName { content, _ = s.Attr("content") return false } attr, exists = s.Attr("itemprop") if exists && attr == metaName { content, _ = s.Attr("content") return false } return true }) return content }
go
func (extr *ContentExtractor) GetMetaContent(document *goquery.Document, metaName string) string { content := "" document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool { attr, exists := s.Attr("name") if exists && attr == metaName { content, _ = s.Attr("content") return false } attr, exists = s.Attr("itemprop") if exists && attr == metaName { content, _ = s.Attr("content") return false } return true }) return content }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetMetaContent", "(", "document", "*", "goquery", ".", "Document", ",", "metaName", "string", ")", "string", "{", "content", ":=", "\"", "\"", "\n", "document", ".", "Find", "(", "\"", "\"", ")", ".", ...
// GetMetaContent returns the content attribute of meta tag with the given property name
[ "GetMetaContent", "returns", "the", "content", "attribute", "of", "meta", "tag", "with", "the", "given", "property", "name" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L170-L186
1,986
advancedlogic/GoOse
extractor.go
GetMetaContents
func (extr *ContentExtractor) GetMetaContents(document *goquery.Document, metaNames *set.Set) map[string]string { contents := make(map[string]string) counter := metaNames.Size() document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool { attr, exists := s.Attr("name") if exists && metaNames.Has(attr) { content, _ := s.Attr("content") contents[attr] = content counter-- if counter < 0 { return false } } return true }) return contents }
go
func (extr *ContentExtractor) GetMetaContents(document *goquery.Document, metaNames *set.Set) map[string]string { contents := make(map[string]string) counter := metaNames.Size() document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool { attr, exists := s.Attr("name") if exists && metaNames.Has(attr) { content, _ := s.Attr("content") contents[attr] = content counter-- if counter < 0 { return false } } return true }) return contents }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetMetaContents", "(", "document", "*", "goquery", ".", "Document", ",", "metaNames", "*", "set", ".", "Set", ")", "map", "[", "string", "]", "string", "{", "contents", ":=", "make", "(", "map", "[", ...
// GetMetaContents returns all the meta tags as name->content pairs
[ "GetMetaContents", "returns", "all", "the", "meta", "tags", "as", "name", "-", ">", "content", "pairs" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L189-L205
1,987
advancedlogic/GoOse
extractor.go
GetMetaDescription
func (extr *ContentExtractor) GetMetaDescription(document *goquery.Document) string { return extr.GetMetaContent(document, "description") }
go
func (extr *ContentExtractor) GetMetaDescription(document *goquery.Document) string { return extr.GetMetaContent(document, "description") }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetMetaDescription", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "return", "extr", ".", "GetMetaContent", "(", "document", ",", "\"", "\"", ")", "\n", "}" ]
// GetMetaDescription returns the meta description set in the source, if the article has one
[ "GetMetaDescription", "returns", "the", "meta", "description", "set", "in", "the", "source", "if", "the", "article", "has", "one" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L208-L210
1,988
advancedlogic/GoOse
extractor.go
GetMetaKeywords
func (extr *ContentExtractor) GetMetaKeywords(document *goquery.Document) string { return extr.GetMetaContent(document, "keywords") }
go
func (extr *ContentExtractor) GetMetaKeywords(document *goquery.Document) string { return extr.GetMetaContent(document, "keywords") }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetMetaKeywords", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "return", "extr", ".", "GetMetaContent", "(", "document", ",", "\"", "\"", ")", "\n", "}" ]
// GetMetaKeywords returns the meta keywords set in the source, if the article has them
[ "GetMetaKeywords", "returns", "the", "meta", "keywords", "set", "in", "the", "source", "if", "the", "article", "has", "them" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L213-L215
1,989
advancedlogic/GoOse
extractor.go
GetMetaAuthor
func (extr *ContentExtractor) GetMetaAuthor(document *goquery.Document) string { return extr.GetMetaContent(document, "author") }
go
func (extr *ContentExtractor) GetMetaAuthor(document *goquery.Document) string { return extr.GetMetaContent(document, "author") }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetMetaAuthor", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "return", "extr", ".", "GetMetaContent", "(", "document", ",", "\"", "\"", ")", "\n", "}" ]
// GetMetaAuthor returns the meta author set in the source, if the article has one
[ "GetMetaAuthor", "returns", "the", "meta", "author", "set", "in", "the", "source", "if", "the", "article", "has", "one" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L218-L220
1,990
advancedlogic/GoOse
extractor.go
GetMetaContentLocation
func (extr *ContentExtractor) GetMetaContentLocation(document *goquery.Document) string { return extr.GetMetaContent(document, "contentLocation") }
go
func (extr *ContentExtractor) GetMetaContentLocation(document *goquery.Document) string { return extr.GetMetaContent(document, "contentLocation") }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetMetaContentLocation", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "return", "extr", ".", "GetMetaContent", "(", "document", ",", "\"", "\"", ")", "\n", "}" ]
// GetMetaContentLocation returns the meta content location set in the source, if the article has one
[ "GetMetaContentLocation", "returns", "the", "meta", "content", "location", "set", "in", "the", "source", "if", "the", "article", "has", "one" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L223-L225
1,991
advancedlogic/GoOse
extractor.go
GetCanonicalLink
func (extr *ContentExtractor) GetCanonicalLink(document *goquery.Document) string { metas := document.Find("link[rel=canonical]") if metas.Length() > 0 { meta := metas.First() href, _ := meta.Attr("href") href = strings.Trim(href, "\n") href = strings.Trim(href, " ") if href != "" { return href } } return "" }
go
func (extr *ContentExtractor) GetCanonicalLink(document *goquery.Document) string { metas := document.Find("link[rel=canonical]") if metas.Length() > 0 { meta := metas.First() href, _ := meta.Attr("href") href = strings.Trim(href, "\n") href = strings.Trim(href, " ") if href != "" { return href } } return "" }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetCanonicalLink", "(", "document", "*", "goquery", ".", "Document", ")", "string", "{", "metas", ":=", "document", ".", "Find", "(", "\"", "\"", ")", "\n", "if", "metas", ".", "Length", "(", ")", ">"...
// GetCanonicalLink returns the meta canonical link set in the source
[ "GetCanonicalLink", "returns", "the", "meta", "canonical", "link", "set", "in", "the", "source" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L228-L240
1,992
advancedlogic/GoOse
extractor.go
GetDomain
func (extr *ContentExtractor) GetDomain(canonicalLink string) string { u, err := url.Parse(canonicalLink) if err == nil { return u.Host } return "" }
go
func (extr *ContentExtractor) GetDomain(canonicalLink string) string { u, err := url.Parse(canonicalLink) if err == nil { return u.Host } return "" }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetDomain", "(", "canonicalLink", "string", ")", "string", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "canonicalLink", ")", "\n", "if", "err", "==", "nil", "{", "return", "u", ".", "Host", ...
// GetDomain extracts the domain from a link
[ "GetDomain", "extracts", "the", "domain", "from", "a", "link" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L243-L249
1,993
advancedlogic/GoOse
extractor.go
GetTags
func (extr *ContentExtractor) GetTags(document *goquery.Document) *set.Set { tags := set.New(set.ThreadSafe).(*set.Set) selections := document.Find(aRelTagSelector) selections.Each(func(i int, s *goquery.Selection) { tags.Add(s.Text()) }) selections = document.Find("a") selections.Each(func(i int, s *goquery.Selection) { href, exists := s.Attr("href") if exists { for _, part := range aHrefTagSelector { if strings.Contains(href, part) { tags.Add(s.Text()) } } } }) return tags }
go
func (extr *ContentExtractor) GetTags(document *goquery.Document) *set.Set { tags := set.New(set.ThreadSafe).(*set.Set) selections := document.Find(aRelTagSelector) selections.Each(func(i int, s *goquery.Selection) { tags.Add(s.Text()) }) selections = document.Find("a") selections.Each(func(i int, s *goquery.Selection) { href, exists := s.Attr("href") if exists { for _, part := range aHrefTagSelector { if strings.Contains(href, part) { tags.Add(s.Text()) } } } }) return tags }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetTags", "(", "document", "*", "goquery", ".", "Document", ")", "*", "set", ".", "Set", "{", "tags", ":=", "set", ".", "New", "(", "set", ".", "ThreadSafe", ")", ".", "(", "*", "set", ".", "Set",...
// GetTags returns the tags set in the source, if the article has them
[ "GetTags", "returns", "the", "tags", "set", "in", "the", "source", "if", "the", "article", "has", "them" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L252-L271
1,994
advancedlogic/GoOse
extractor.go
GetPublishDate
func (extr *ContentExtractor) GetPublishDate(document *goquery.Document) *time.Time { raw, err := document.Html() if err != nil { log.Printf("Error converting document HTML nodes to raw HTML: %s (publish date detection aborted)\n", err) return nil } text, err := html2text.FromString(raw) if err != nil { log.Printf("Error converting document HTML to plaintext: %s (publish date detection aborted)\n", err) return nil } text = strings.ToLower(text) // Simplify months because the dateparse pkg only handles abbreviated. for k, v := range map[string]string{ "january": "jan", "march": "mar", "february": "feb", "april": "apr", // "may": "may", // Pointless. "june": "jun", "august": "aug", "september": "sep", "sept": "sep", "october": "oct", "november": "nov", "december": "dec", "th,": ",", // Strip day number suffixes. "rd,": ",", } { text = strings.Replace(text, k, v, -1) } text = strings.Replace(text, "\n", " ", -1) text = regexp.MustCompile(" +").ReplaceAllString(text, " ") tuple1 := strings.Split(text, " ") var ( expr = regexp.MustCompile("[0-9]") ts time.Time found bool ) for _, n := range []int{3, 4, 5, 2, 6} { for _, win := range window.Rolling(tuple1, n) { if !expr.MatchString(strings.Join(win, " ")) { continue } input := strings.Join(win, " ") ts, err = dateparse.ParseAny(input) if err == nil && ts.Year() > 0 && ts.Month() > 0 && ts.Day() > 0 { found = true break } // Try injecting a comma for dateparse. win[1] = win[1] + "," input = strings.Join(win, " ") ts, err = dateparse.ParseAny(input) if err == nil && ts.Year() > 0 && ts.Month() > 0 && ts.Day() > 0 { found = true break } } if found { break } } if found { return &ts } return nil }
go
func (extr *ContentExtractor) GetPublishDate(document *goquery.Document) *time.Time { raw, err := document.Html() if err != nil { log.Printf("Error converting document HTML nodes to raw HTML: %s (publish date detection aborted)\n", err) return nil } text, err := html2text.FromString(raw) if err != nil { log.Printf("Error converting document HTML to plaintext: %s (publish date detection aborted)\n", err) return nil } text = strings.ToLower(text) // Simplify months because the dateparse pkg only handles abbreviated. for k, v := range map[string]string{ "january": "jan", "march": "mar", "february": "feb", "april": "apr", // "may": "may", // Pointless. "june": "jun", "august": "aug", "september": "sep", "sept": "sep", "october": "oct", "november": "nov", "december": "dec", "th,": ",", // Strip day number suffixes. "rd,": ",", } { text = strings.Replace(text, k, v, -1) } text = strings.Replace(text, "\n", " ", -1) text = regexp.MustCompile(" +").ReplaceAllString(text, " ") tuple1 := strings.Split(text, " ") var ( expr = regexp.MustCompile("[0-9]") ts time.Time found bool ) for _, n := range []int{3, 4, 5, 2, 6} { for _, win := range window.Rolling(tuple1, n) { if !expr.MatchString(strings.Join(win, " ")) { continue } input := strings.Join(win, " ") ts, err = dateparse.ParseAny(input) if err == nil && ts.Year() > 0 && ts.Month() > 0 && ts.Day() > 0 { found = true break } // Try injecting a comma for dateparse. win[1] = win[1] + "," input = strings.Join(win, " ") ts, err = dateparse.ParseAny(input) if err == nil && ts.Year() > 0 && ts.Month() > 0 && ts.Day() > 0 { found = true break } } if found { break } } if found { return &ts } return nil }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetPublishDate", "(", "document", "*", "goquery", ".", "Document", ")", "*", "time", ".", "Time", "{", "raw", ",", "err", ":=", "document", ".", "Html", "(", ")", "\n", "if", "err", "!=", "nil", "{"...
// GetPublishDate returns the publication date, if one can be located.
[ "GetPublishDate", "returns", "the", "publication", "date", "if", "one", "can", "be", "located", "." ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L274-L349
1,995
advancedlogic/GoOse
extractor.go
GetCleanTextAndLinks
func (extr *ContentExtractor) GetCleanTextAndLinks(topNode *goquery.Selection, lang string) (string, []string) { outputFormatter := new(outputFormatter) outputFormatter.config = extr.config return outputFormatter.getFormattedText(topNode, lang) }
go
func (extr *ContentExtractor) GetCleanTextAndLinks(topNode *goquery.Selection, lang string) (string, []string) { outputFormatter := new(outputFormatter) outputFormatter.config = extr.config return outputFormatter.getFormattedText(topNode, lang) }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "GetCleanTextAndLinks", "(", "topNode", "*", "goquery", ".", "Selection", ",", "lang", "string", ")", "(", "string", ",", "[", "]", "string", ")", "{", "outputFormatter", ":=", "new", "(", "outputFormatter",...
// GetCleanTextAndLinks parses the main HTML node for text and links
[ "GetCleanTextAndLinks", "parses", "the", "main", "HTML", "node", "for", "text", "and", "links" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L352-L356
1,996
advancedlogic/GoOse
extractor.go
getScore
func (extr *ContentExtractor) getScore(node *goquery.Selection) int { return extr.getNodeGravityScore(node) }
go
func (extr *ContentExtractor) getScore(node *goquery.Selection) int { return extr.getNodeGravityScore(node) }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "getScore", "(", "node", "*", "goquery", ".", "Selection", ")", "int", "{", "return", "extr", ".", "getNodeGravityScore", "(", "node", ")", "\n", "}" ]
//returns the gravityScore as an integer from this node
[ "returns", "the", "gravityScore", "as", "an", "integer", "from", "this", "node" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L454-L456
1,997
advancedlogic/GoOse
extractor.go
updateScore
func (extr *ContentExtractor) updateScore(node *goquery.Selection, addToScore int) { currentScore := 0 var err error scoreString, _ := node.Attr("gravityScore") if scoreString != "" { currentScore, err = strconv.Atoi(scoreString) if err != nil { currentScore = 0 } } newScore := currentScore + addToScore extr.config.parser.setAttr(node, "gravityScore", strconv.Itoa(newScore)) }
go
func (extr *ContentExtractor) updateScore(node *goquery.Selection, addToScore int) { currentScore := 0 var err error scoreString, _ := node.Attr("gravityScore") if scoreString != "" { currentScore, err = strconv.Atoi(scoreString) if err != nil { currentScore = 0 } } newScore := currentScore + addToScore extr.config.parser.setAttr(node, "gravityScore", strconv.Itoa(newScore)) }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "updateScore", "(", "node", "*", "goquery", ".", "Selection", ",", "addToScore", "int", ")", "{", "currentScore", ":=", "0", "\n", "var", "err", "error", "\n", "scoreString", ",", "_", ":=", "node", ".",...
//adds a score to the gravityScore Attribute we put on divs //we'll get the current score then add the score we're passing in to the current
[ "adds", "a", "score", "to", "the", "gravityScore", "Attribute", "we", "put", "on", "divs", "we", "ll", "get", "the", "current", "score", "then", "add", "the", "score", "we", "re", "passing", "in", "to", "the", "current" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L472-L484
1,998
advancedlogic/GoOse
extractor.go
isBoostable
func (extr *ContentExtractor) isBoostable(node *goquery.Selection) bool { stepsAway := 0 next := node.Next() for next != nil && stepsAway < node.Siblings().Length() { currentNodeTag := node.Get(0).DataAtom.String() if currentNodeTag == "p" { if stepsAway >= 3 { if extr.config.debug { log.Println("Next paragraph is too far away, not boosting") } return false } paraText := node.Text() ws := extr.config.stopWords.stopWordsCount(extr.config.targetLanguage, paraText) if ws.stopWordCount > 5 { if extr.config.debug { log.Println("We're gonna boost this node, seems content") } return true } } stepsAway++ next = next.Next() } return false }
go
func (extr *ContentExtractor) isBoostable(node *goquery.Selection) bool { stepsAway := 0 next := node.Next() for next != nil && stepsAway < node.Siblings().Length() { currentNodeTag := node.Get(0).DataAtom.String() if currentNodeTag == "p" { if stepsAway >= 3 { if extr.config.debug { log.Println("Next paragraph is too far away, not boosting") } return false } paraText := node.Text() ws := extr.config.stopWords.stopWordsCount(extr.config.targetLanguage, paraText) if ws.stopWordCount > 5 { if extr.config.debug { log.Println("We're gonna boost this node, seems content") } return true } } stepsAway++ next = next.Next() } return false }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "isBoostable", "(", "node", "*", "goquery", ".", "Selection", ")", "bool", "{", "stepsAway", ":=", "0", "\n", "next", ":=", "node", ".", "Next", "(", ")", "\n", "for", "next", "!=", "nil", "&&", "ste...
//a lot of times the first paragraph might be the caption under an image so we'll want to make sure if we're going to //boost a parent node that it should be connected to other paragraphs, at least for the first n paragraphs //so we'll want to make sure that the next sibling is a paragraph and has at least some substantial weight to it
[ "a", "lot", "of", "times", "the", "first", "paragraph", "might", "be", "the", "caption", "under", "an", "image", "so", "we", "ll", "want", "to", "make", "sure", "if", "we", "re", "going", "to", "boost", "a", "parent", "node", "that", "it", "should", ...
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L504-L532
1,999
advancedlogic/GoOse
extractor.go
nodesToCheck
func (extr *ContentExtractor) nodesToCheck(doc *goquery.Document) []*goquery.Selection { var output []*goquery.Selection tags := []string{"p", "pre", "td"} for _, tag := range tags { selections := doc.Children().Find(tag) if selections != nil { selections.Each(func(i int, s *goquery.Selection) { output = append(output, s) }) } } return output }
go
func (extr *ContentExtractor) nodesToCheck(doc *goquery.Document) []*goquery.Selection { var output []*goquery.Selection tags := []string{"p", "pre", "td"} for _, tag := range tags { selections := doc.Children().Find(tag) if selections != nil { selections.Each(func(i int, s *goquery.Selection) { output = append(output, s) }) } } return output }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "nodesToCheck", "(", "doc", "*", "goquery", ".", "Document", ")", "[", "]", "*", "goquery", ".", "Selection", "{", "var", "output", "[", "]", "*", "goquery", ".", "Selection", "\n", "tags", ":=", "[", ...
//returns a list of nodes we want to search on like paragraphs and tables
[ "returns", "a", "list", "of", "nodes", "we", "want", "to", "search", "on", "like", "paragraphs", "and", "tables" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L535-L547