id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
146,700
go-ini/ini
struct.go
setWithProperType
func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { switch t.Kind() { case reflect.String: if len(key.String()) == 0 { return nil } field.SetString(key.String()) case reflect.Bool: boolVal, err := key.Bool() if err != nil { return wrapStrictError(err, isStrict) } field.SetBool(boolVal) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: durationVal, err := key.Duration() // Skip zero value if err == nil && int64(durationVal) > 0 { field.Set(reflect.ValueOf(durationVal)) return nil } intVal, err := key.Int64() if err != nil { return wrapStrictError(err, isStrict) } field.SetInt(intVal) // byte is an alias for uint8, so supporting uint8 breaks support for byte case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: durationVal, err := key.Duration() // Skip zero value if err == nil && uint64(durationVal) > 0 { field.Set(reflect.ValueOf(durationVal)) return nil } uintVal, err := key.Uint64() if err != nil { return wrapStrictError(err, isStrict) } field.SetUint(uintVal) case reflect.Float32, reflect.Float64: floatVal, err := key.Float64() if err != nil { return wrapStrictError(err, isStrict) } field.SetFloat(floatVal) case reflectTime: timeVal, err := key.Time() if err != nil { return wrapStrictError(err, isStrict) } field.Set(reflect.ValueOf(timeVal)) case reflect.Slice: return setSliceWithProperType(key, field, delim, allowShadow, isStrict) default: return fmt.Errorf("unsupported type '%s'", t) } return nil }
go
func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { switch t.Kind() { case reflect.String: if len(key.String()) == 0 { return nil } field.SetString(key.String()) case reflect.Bool: boolVal, err := key.Bool() if err != nil { return wrapStrictError(err, isStrict) } field.SetBool(boolVal) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: durationVal, err := key.Duration() // Skip zero value if err == nil && int64(durationVal) > 0 { field.Set(reflect.ValueOf(durationVal)) return nil } intVal, err := key.Int64() if err != nil { return wrapStrictError(err, isStrict) } field.SetInt(intVal) // byte is an alias for uint8, so supporting uint8 breaks support for byte case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: durationVal, err := key.Duration() // Skip zero value if err == nil && uint64(durationVal) > 0 { field.Set(reflect.ValueOf(durationVal)) return nil } uintVal, err := key.Uint64() if err != nil { return wrapStrictError(err, isStrict) } field.SetUint(uintVal) case reflect.Float32, reflect.Float64: floatVal, err := key.Float64() if err != nil { return wrapStrictError(err, isStrict) } field.SetFloat(floatVal) case reflectTime: timeVal, err := key.Time() if err != nil { return wrapStrictError(err, isStrict) } field.Set(reflect.ValueOf(timeVal)) case reflect.Slice: return setSliceWithProperType(key, field, delim, allowShadow, isStrict) default: return fmt.Errorf("unsupported type '%s'", t) } return nil }
[ "func", "setWithProperType", "(", "t", "reflect", ".", "Type", ",", "key", "*", "Key", ",", "field", "reflect", ".", "Value", ",", "delim", "string", ",", "allowShadow", ",", "isStrict", "bool", ")", "error", "{", "switch", "t", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "String", ":", "if", "len", "(", "key", ".", "String", "(", ")", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "field", ".", "SetString", "(", "key", ".", "String", "(", ")", ")", "\n", "case", "reflect", ".", "Bool", ":", "boolVal", ",", "err", ":=", "key", ".", "Bool", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapStrictError", "(", "err", ",", "isStrict", ")", "\n", "}", "\n", "field", ".", "SetBool", "(", "boolVal", ")", "\n", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ":", "durationVal", ",", "err", ":=", "key", ".", "Duration", "(", ")", "\n", "// Skip zero value", "if", "err", "==", "nil", "&&", "int64", "(", "durationVal", ")", ">", "0", "{", "field", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "durationVal", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "intVal", ",", "err", ":=", "key", ".", "Int64", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapStrictError", "(", "err", ",", "isStrict", ")", "\n", "}", "\n", "field", ".", "SetInt", "(", "intVal", ")", "\n", "//\tbyte is an alias for uint8, so supporting uint8 breaks support for byte", "case", "reflect", ".", "Uint", ",", "reflect", ".", "Uint16", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint64", ":", "durationVal", ",", "err", ":=", "key", ".", "Duration", "(", ")", "\n", "// Skip zero value", "if", "err", "==", "nil", "&&", "uint64", "(", "durationVal", ")", ">", "0", "{", "field", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "durationVal", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "uintVal", ",", "err", ":=", "key", ".", "Uint64", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapStrictError", "(", "err", ",", "isStrict", ")", "\n", "}", "\n", "field", ".", "SetUint", "(", "uintVal", ")", "\n\n", "case", "reflect", ".", "Float32", ",", "reflect", ".", "Float64", ":", "floatVal", ",", "err", ":=", "key", ".", "Float64", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapStrictError", "(", "err", ",", "isStrict", ")", "\n", "}", "\n", "field", ".", "SetFloat", "(", "floatVal", ")", "\n", "case", "reflectTime", ":", "timeVal", ",", "err", ":=", "key", ".", "Time", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapStrictError", "(", "err", ",", "isStrict", ")", "\n", "}", "\n", "field", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "timeVal", ")", ")", "\n", "case", "reflect", ".", "Slice", ":", "return", "setSliceWithProperType", "(", "key", ",", "field", ",", "delim", ",", "allowShadow", ",", "isStrict", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// setWithProperType sets proper value to field based on its type, // but it does not return error for failing parsing, // because we want to use default value that is already assigned to strcut.
[ "setWithProperType", "sets", "proper", "value", "to", "field", "based", "on", "its", "type", "but", "it", "does", "not", "return", "error", "for", "failing", "parsing", "because", "we", "want", "to", "use", "default", "value", "that", "is", "already", "assigned", "to", "strcut", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L153-L212
146,701
go-ini/ini
struct.go
MapTo
func (s *Section) MapTo(v interface{}) error { typ := reflect.TypeOf(v) val := reflect.ValueOf(v) if typ.Kind() == reflect.Ptr { typ = typ.Elem() val = val.Elem() } else { return errors.New("cannot map to non-pointer struct") } return s.mapTo(val, false) }
go
func (s *Section) MapTo(v interface{}) error { typ := reflect.TypeOf(v) val := reflect.ValueOf(v) if typ.Kind() == reflect.Ptr { typ = typ.Elem() val = val.Elem() } else { return errors.New("cannot map to non-pointer struct") } return s.mapTo(val, false) }
[ "func", "(", "s", "*", "Section", ")", "MapTo", "(", "v", "interface", "{", "}", ")", "error", "{", "typ", ":=", "reflect", ".", "TypeOf", "(", "v", ")", "\n", "val", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "if", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "typ", "=", "typ", ".", "Elem", "(", ")", "\n", "val", "=", "val", ".", "Elem", "(", ")", "\n", "}", "else", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "s", ".", "mapTo", "(", "val", ",", "false", ")", "\n", "}" ]
// MapTo maps section to given struct.
[ "MapTo", "maps", "section", "to", "given", "struct", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L273-L284
146,702
go-ini/ini
struct.go
StrictMapTo
func (s *Section) StrictMapTo(v interface{}) error { typ := reflect.TypeOf(v) val := reflect.ValueOf(v) if typ.Kind() == reflect.Ptr { typ = typ.Elem() val = val.Elem() } else { return errors.New("cannot map to non-pointer struct") } return s.mapTo(val, true) }
go
func (s *Section) StrictMapTo(v interface{}) error { typ := reflect.TypeOf(v) val := reflect.ValueOf(v) if typ.Kind() == reflect.Ptr { typ = typ.Elem() val = val.Elem() } else { return errors.New("cannot map to non-pointer struct") } return s.mapTo(val, true) }
[ "func", "(", "s", "*", "Section", ")", "StrictMapTo", "(", "v", "interface", "{", "}", ")", "error", "{", "typ", ":=", "reflect", ".", "TypeOf", "(", "v", ")", "\n", "val", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "if", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "typ", "=", "typ", ".", "Elem", "(", ")", "\n", "val", "=", "val", ".", "Elem", "(", ")", "\n", "}", "else", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "s", ".", "mapTo", "(", "val", ",", "true", ")", "\n", "}" ]
// StrictMapTo maps section to given struct in strict mode, // which returns all possible error including value parsing error.
[ "StrictMapTo", "maps", "section", "to", "given", "struct", "in", "strict", "mode", "which", "returns", "all", "possible", "error", "including", "value", "parsing", "error", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L288-L299
146,703
go-ini/ini
struct.go
MapToWithMapper
func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { cfg, err := Load(source, others...) if err != nil { return err } cfg.NameMapper = mapper return cfg.MapTo(v) }
go
func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { cfg, err := Load(source, others...) if err != nil { return err } cfg.NameMapper = mapper return cfg.MapTo(v) }
[ "func", "MapToWithMapper", "(", "v", "interface", "{", "}", ",", "mapper", "NameMapper", ",", "source", "interface", "{", "}", ",", "others", "...", "interface", "{", "}", ")", "error", "{", "cfg", ",", "err", ":=", "Load", "(", "source", ",", "others", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cfg", ".", "NameMapper", "=", "mapper", "\n", "return", "cfg", ".", "MapTo", "(", "v", ")", "\n", "}" ]
// MapToWithMapper maps data sources to given struct with name mapper.
[ "MapToWithMapper", "maps", "data", "sources", "to", "given", "struct", "with", "name", "mapper", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L313-L320
146,704
go-ini/ini
struct.go
StrictMapToWithMapper
func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { cfg, err := Load(source, others...) if err != nil { return err } cfg.NameMapper = mapper return cfg.StrictMapTo(v) }
go
func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { cfg, err := Load(source, others...) if err != nil { return err } cfg.NameMapper = mapper return cfg.StrictMapTo(v) }
[ "func", "StrictMapToWithMapper", "(", "v", "interface", "{", "}", ",", "mapper", "NameMapper", ",", "source", "interface", "{", "}", ",", "others", "...", "interface", "{", "}", ")", "error", "{", "cfg", ",", "err", ":=", "Load", "(", "source", ",", "others", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cfg", ".", "NameMapper", "=", "mapper", "\n", "return", "cfg", ".", "StrictMapTo", "(", "v", ")", "\n", "}" ]
// StrictMapToWithMapper maps data sources to given struct with name mapper in strict mode, // which returns all possible error including value parsing error.
[ "StrictMapToWithMapper", "maps", "data", "sources", "to", "given", "struct", "with", "name", "mapper", "in", "strict", "mode", "which", "returns", "all", "possible", "error", "including", "value", "parsing", "error", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L324-L331
146,705
go-ini/ini
struct.go
MapTo
func MapTo(v, source interface{}, others ...interface{}) error { return MapToWithMapper(v, nil, source, others...) }
go
func MapTo(v, source interface{}, others ...interface{}) error { return MapToWithMapper(v, nil, source, others...) }
[ "func", "MapTo", "(", "v", ",", "source", "interface", "{", "}", ",", "others", "...", "interface", "{", "}", ")", "error", "{", "return", "MapToWithMapper", "(", "v", ",", "nil", ",", "source", ",", "others", "...", ")", "\n", "}" ]
// MapTo maps data sources to given struct.
[ "MapTo", "maps", "data", "sources", "to", "given", "struct", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L334-L336
146,706
go-ini/ini
struct.go
StrictMapTo
func StrictMapTo(v, source interface{}, others ...interface{}) error { return StrictMapToWithMapper(v, nil, source, others...) }
go
func StrictMapTo(v, source interface{}, others ...interface{}) error { return StrictMapToWithMapper(v, nil, source, others...) }
[ "func", "StrictMapTo", "(", "v", ",", "source", "interface", "{", "}", ",", "others", "...", "interface", "{", "}", ")", "error", "{", "return", "StrictMapToWithMapper", "(", "v", ",", "nil", ",", "source", ",", "others", "...", ")", "\n", "}" ]
// StrictMapTo maps data sources to given struct in strict mode, // which returns all possible error including value parsing error.
[ "StrictMapTo", "maps", "data", "sources", "to", "given", "struct", "in", "strict", "mode", "which", "returns", "all", "possible", "error", "including", "value", "parsing", "error", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L340-L342
146,707
go-ini/ini
struct.go
reflectSliceWithProperType
func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error { slice := field.Slice(0, field.Len()) if field.Len() == 0 { return nil } var buf bytes.Buffer sliceOf := field.Type().Elem().Kind() for i := 0; i < field.Len(); i++ { switch sliceOf { case reflect.String: buf.WriteString(slice.Index(i).String()) case reflect.Int, reflect.Int64: buf.WriteString(fmt.Sprint(slice.Index(i).Int())) case reflect.Uint, reflect.Uint64: buf.WriteString(fmt.Sprint(slice.Index(i).Uint())) case reflect.Float64: buf.WriteString(fmt.Sprint(slice.Index(i).Float())) case reflectTime: buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339)) default: return fmt.Errorf("unsupported type '[]%s'", sliceOf) } buf.WriteString(delim) } key.SetValue(buf.String()[:buf.Len()-1]) return nil }
go
func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error { slice := field.Slice(0, field.Len()) if field.Len() == 0 { return nil } var buf bytes.Buffer sliceOf := field.Type().Elem().Kind() for i := 0; i < field.Len(); i++ { switch sliceOf { case reflect.String: buf.WriteString(slice.Index(i).String()) case reflect.Int, reflect.Int64: buf.WriteString(fmt.Sprint(slice.Index(i).Int())) case reflect.Uint, reflect.Uint64: buf.WriteString(fmt.Sprint(slice.Index(i).Uint())) case reflect.Float64: buf.WriteString(fmt.Sprint(slice.Index(i).Float())) case reflectTime: buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339)) default: return fmt.Errorf("unsupported type '[]%s'", sliceOf) } buf.WriteString(delim) } key.SetValue(buf.String()[:buf.Len()-1]) return nil }
[ "func", "reflectSliceWithProperType", "(", "key", "*", "Key", ",", "field", "reflect", ".", "Value", ",", "delim", "string", ")", "error", "{", "slice", ":=", "field", ".", "Slice", "(", "0", ",", "field", ".", "Len", "(", ")", ")", "\n", "if", "field", ".", "Len", "(", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n", "sliceOf", ":=", "field", ".", "Type", "(", ")", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "field", ".", "Len", "(", ")", ";", "i", "++", "{", "switch", "sliceOf", "{", "case", "reflect", ".", "String", ":", "buf", ".", "WriteString", "(", "slice", ".", "Index", "(", "i", ")", ".", "String", "(", ")", ")", "\n", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int64", ":", "buf", ".", "WriteString", "(", "fmt", ".", "Sprint", "(", "slice", ".", "Index", "(", "i", ")", ".", "Int", "(", ")", ")", ")", "\n", "case", "reflect", ".", "Uint", ",", "reflect", ".", "Uint64", ":", "buf", ".", "WriteString", "(", "fmt", ".", "Sprint", "(", "slice", ".", "Index", "(", "i", ")", ".", "Uint", "(", ")", ")", ")", "\n", "case", "reflect", ".", "Float64", ":", "buf", ".", "WriteString", "(", "fmt", ".", "Sprint", "(", "slice", ".", "Index", "(", "i", ")", ".", "Float", "(", ")", ")", ")", "\n", "case", "reflectTime", ":", "buf", ".", "WriteString", "(", "slice", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", ".", "(", "time", ".", "Time", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sliceOf", ")", "\n", "}", "\n", "buf", ".", "WriteString", "(", "delim", ")", "\n", "}", "\n", "key", ".", "SetValue", "(", "buf", ".", "String", "(", ")", "[", ":", "buf", ".", "Len", "(", ")", "-", "1", "]", ")", "\n", "return", "nil", "\n", "}" ]
// reflectSliceWithProperType does the opposite thing as setSliceWithProperType.
[ "reflectSliceWithProperType", "does", "the", "opposite", "thing", "as", "setSliceWithProperType", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L345-L372
146,708
go-ini/ini
struct.go
reflectWithProperType
func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { switch t.Kind() { case reflect.String: key.SetValue(field.String()) case reflect.Bool: key.SetValue(fmt.Sprint(field.Bool())) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: key.SetValue(fmt.Sprint(field.Int())) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: key.SetValue(fmt.Sprint(field.Uint())) case reflect.Float32, reflect.Float64: key.SetValue(fmt.Sprint(field.Float())) case reflectTime: key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339))) case reflect.Slice: return reflectSliceWithProperType(key, field, delim) default: return fmt.Errorf("unsupported type '%s'", t) } return nil }
go
func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { switch t.Kind() { case reflect.String: key.SetValue(field.String()) case reflect.Bool: key.SetValue(fmt.Sprint(field.Bool())) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: key.SetValue(fmt.Sprint(field.Int())) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: key.SetValue(fmt.Sprint(field.Uint())) case reflect.Float32, reflect.Float64: key.SetValue(fmt.Sprint(field.Float())) case reflectTime: key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339))) case reflect.Slice: return reflectSliceWithProperType(key, field, delim) default: return fmt.Errorf("unsupported type '%s'", t) } return nil }
[ "func", "reflectWithProperType", "(", "t", "reflect", ".", "Type", ",", "key", "*", "Key", ",", "field", "reflect", ".", "Value", ",", "delim", "string", ")", "error", "{", "switch", "t", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "String", ":", "key", ".", "SetValue", "(", "field", ".", "String", "(", ")", ")", "\n", "case", "reflect", ".", "Bool", ":", "key", ".", "SetValue", "(", "fmt", ".", "Sprint", "(", "field", ".", "Bool", "(", ")", ")", ")", "\n", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ":", "key", ".", "SetValue", "(", "fmt", ".", "Sprint", "(", "field", ".", "Int", "(", ")", ")", ")", "\n", "case", "reflect", ".", "Uint", ",", "reflect", ".", "Uint8", ",", "reflect", ".", "Uint16", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint64", ":", "key", ".", "SetValue", "(", "fmt", ".", "Sprint", "(", "field", ".", "Uint", "(", ")", ")", ")", "\n", "case", "reflect", ".", "Float32", ",", "reflect", ".", "Float64", ":", "key", ".", "SetValue", "(", "fmt", ".", "Sprint", "(", "field", ".", "Float", "(", ")", ")", ")", "\n", "case", "reflectTime", ":", "key", ".", "SetValue", "(", "fmt", ".", "Sprint", "(", "field", ".", "Interface", "(", ")", ".", "(", "time", ".", "Time", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", ")", ")", "\n", "case", "reflect", ".", "Slice", ":", "return", "reflectSliceWithProperType", "(", "key", ",", "field", ",", "delim", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// reflectWithProperType does the opposite thing as setWithProperType.
[ "reflectWithProperType", "does", "the", "opposite", "thing", "as", "setWithProperType", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L375-L395
146,709
go-ini/ini
struct.go
ReflectFrom
func (s *Section) ReflectFrom(v interface{}) error { typ := reflect.TypeOf(v) val := reflect.ValueOf(v) if typ.Kind() == reflect.Ptr { typ = typ.Elem() val = val.Elem() } else { return errors.New("cannot reflect from non-pointer struct") } return s.reflectFrom(val) }
go
func (s *Section) ReflectFrom(v interface{}) error { typ := reflect.TypeOf(v) val := reflect.ValueOf(v) if typ.Kind() == reflect.Ptr { typ = typ.Elem() val = val.Elem() } else { return errors.New("cannot reflect from non-pointer struct") } return s.reflectFrom(val) }
[ "func", "(", "s", "*", "Section", ")", "ReflectFrom", "(", "v", "interface", "{", "}", ")", "error", "{", "typ", ":=", "reflect", ".", "TypeOf", "(", "v", ")", "\n", "val", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "if", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "typ", "=", "typ", ".", "Elem", "(", ")", "\n", "val", "=", "val", ".", "Elem", "(", ")", "\n", "}", "else", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "s", ".", "reflectFrom", "(", "val", ")", "\n", "}" ]
// ReflectFrom reflects secion from given struct.
[ "ReflectFrom", "reflects", "secion", "from", "given", "struct", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L485-L496
146,710
go-ini/ini
struct.go
ReflectFromWithMapper
func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error { cfg.NameMapper = mapper return cfg.ReflectFrom(v) }
go
func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error { cfg.NameMapper = mapper return cfg.ReflectFrom(v) }
[ "func", "ReflectFromWithMapper", "(", "cfg", "*", "File", ",", "v", "interface", "{", "}", ",", "mapper", "NameMapper", ")", "error", "{", "cfg", ".", "NameMapper", "=", "mapper", "\n", "return", "cfg", ".", "ReflectFrom", "(", "v", ")", "\n", "}" ]
// ReflectFromWithMapper reflects data sources from given struct with name mapper.
[ "ReflectFromWithMapper", "reflects", "data", "sources", "from", "given", "struct", "with", "name", "mapper", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/struct.go#L504-L507
146,711
go-ini/ini
section.go
SetBody
func (s *Section) SetBody(body string) { if !s.isRawSection { return } s.rawBody = body }
go
func (s *Section) SetBody(body string) { if !s.isRawSection { return } s.rawBody = body }
[ "func", "(", "s", "*", "Section", ")", "SetBody", "(", "body", "string", ")", "{", "if", "!", "s", ".", "isRawSection", "{", "return", "\n", "}", "\n", "s", ".", "rawBody", "=", "body", "\n", "}" ]
// SetBody updates body content only if section is raw.
[ "SetBody", "updates", "body", "content", "only", "if", "section", "is", "raw", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L58-L63
146,712
go-ini/ini
section.go
NewKey
func (s *Section) NewKey(name, val string) (*Key, error) { if len(name) == 0 { return nil, errors.New("error creating new key: empty key name") } else if s.f.options.Insensitive { name = strings.ToLower(name) } if s.f.BlockMode { s.f.lock.Lock() defer s.f.lock.Unlock() } if inSlice(name, s.keyList) { if s.f.options.AllowShadows { if err := s.keys[name].addShadow(val); err != nil { return nil, err } } else { s.keys[name].value = val s.keysHash[name] = val } return s.keys[name], nil } s.keyList = append(s.keyList, name) s.keys[name] = newKey(s, name, val) s.keysHash[name] = val return s.keys[name], nil }
go
func (s *Section) NewKey(name, val string) (*Key, error) { if len(name) == 0 { return nil, errors.New("error creating new key: empty key name") } else if s.f.options.Insensitive { name = strings.ToLower(name) } if s.f.BlockMode { s.f.lock.Lock() defer s.f.lock.Unlock() } if inSlice(name, s.keyList) { if s.f.options.AllowShadows { if err := s.keys[name].addShadow(val); err != nil { return nil, err } } else { s.keys[name].value = val s.keysHash[name] = val } return s.keys[name], nil } s.keyList = append(s.keyList, name) s.keys[name] = newKey(s, name, val) s.keysHash[name] = val return s.keys[name], nil }
[ "func", "(", "s", "*", "Section", ")", "NewKey", "(", "name", ",", "val", "string", ")", "(", "*", "Key", ",", "error", ")", "{", "if", "len", "(", "name", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "if", "s", ".", "f", ".", "options", ".", "Insensitive", "{", "name", "=", "strings", ".", "ToLower", "(", "name", ")", "\n", "}", "\n\n", "if", "s", ".", "f", ".", "BlockMode", "{", "s", ".", "f", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "f", ".", "lock", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "if", "inSlice", "(", "name", ",", "s", ".", "keyList", ")", "{", "if", "s", ".", "f", ".", "options", ".", "AllowShadows", "{", "if", "err", ":=", "s", ".", "keys", "[", "name", "]", ".", "addShadow", "(", "val", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "s", ".", "keys", "[", "name", "]", ".", "value", "=", "val", "\n", "s", ".", "keysHash", "[", "name", "]", "=", "val", "\n", "}", "\n", "return", "s", ".", "keys", "[", "name", "]", ",", "nil", "\n", "}", "\n\n", "s", ".", "keyList", "=", "append", "(", "s", ".", "keyList", ",", "name", ")", "\n", "s", ".", "keys", "[", "name", "]", "=", "newKey", "(", "s", ",", "name", ",", "val", ")", "\n", "s", ".", "keysHash", "[", "name", "]", "=", "val", "\n", "return", "s", ".", "keys", "[", "name", "]", ",", "nil", "\n", "}" ]
// NewKey creates a new key to given section.
[ "NewKey", "creates", "a", "new", "key", "to", "given", "section", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L66-L94
146,713
go-ini/ini
section.go
NewBooleanKey
func (s *Section) NewBooleanKey(name string) (*Key, error) { key, err := s.NewKey(name, "true") if err != nil { return nil, err } key.isBooleanType = true return key, nil }
go
func (s *Section) NewBooleanKey(name string) (*Key, error) { key, err := s.NewKey(name, "true") if err != nil { return nil, err } key.isBooleanType = true return key, nil }
[ "func", "(", "s", "*", "Section", ")", "NewBooleanKey", "(", "name", "string", ")", "(", "*", "Key", ",", "error", ")", "{", "key", ",", "err", ":=", "s", ".", "NewKey", "(", "name", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "key", ".", "isBooleanType", "=", "true", "\n", "return", "key", ",", "nil", "\n", "}" ]
// NewBooleanKey creates a new boolean type key to given section.
[ "NewBooleanKey", "creates", "a", "new", "boolean", "type", "key", "to", "given", "section", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L97-L105
146,714
go-ini/ini
section.go
GetKey
func (s *Section) GetKey(name string) (*Key, error) { if s.f.BlockMode { s.f.lock.RLock() } if s.f.options.Insensitive { name = strings.ToLower(name) } key := s.keys[name] if s.f.BlockMode { s.f.lock.RUnlock() } if key == nil { // Check if it is a child-section. sname := s.name for { if i := strings.LastIndex(sname, "."); i > -1 { sname = sname[:i] sec, err := s.f.GetSection(sname) if err != nil { continue } return sec.GetKey(name) } break } return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) } return key, nil }
go
func (s *Section) GetKey(name string) (*Key, error) { if s.f.BlockMode { s.f.lock.RLock() } if s.f.options.Insensitive { name = strings.ToLower(name) } key := s.keys[name] if s.f.BlockMode { s.f.lock.RUnlock() } if key == nil { // Check if it is a child-section. sname := s.name for { if i := strings.LastIndex(sname, "."); i > -1 { sname = sname[:i] sec, err := s.f.GetSection(sname) if err != nil { continue } return sec.GetKey(name) } break } return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) } return key, nil }
[ "func", "(", "s", "*", "Section", ")", "GetKey", "(", "name", "string", ")", "(", "*", "Key", ",", "error", ")", "{", "if", "s", ".", "f", ".", "BlockMode", "{", "s", ".", "f", ".", "lock", ".", "RLock", "(", ")", "\n", "}", "\n", "if", "s", ".", "f", ".", "options", ".", "Insensitive", "{", "name", "=", "strings", ".", "ToLower", "(", "name", ")", "\n", "}", "\n", "key", ":=", "s", ".", "keys", "[", "name", "]", "\n", "if", "s", ".", "f", ".", "BlockMode", "{", "s", ".", "f", ".", "lock", ".", "RUnlock", "(", ")", "\n", "}", "\n\n", "if", "key", "==", "nil", "{", "// Check if it is a child-section.", "sname", ":=", "s", ".", "name", "\n", "for", "{", "if", "i", ":=", "strings", ".", "LastIndex", "(", "sname", ",", "\"", "\"", ")", ";", "i", ">", "-", "1", "{", "sname", "=", "sname", "[", ":", "i", "]", "\n", "sec", ",", "err", ":=", "s", ".", "f", ".", "GetSection", "(", "sname", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "return", "sec", ".", "GetKey", "(", "name", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "name", ",", "name", ")", "\n", "}", "\n", "return", "key", ",", "nil", "\n", "}" ]
// GetKey returns key in section by given name.
[ "GetKey", "returns", "key", "in", "section", "by", "given", "name", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L108-L137
146,715
go-ini/ini
section.go
HasKey
func (s *Section) HasKey(name string) bool { key, _ := s.GetKey(name) return key != nil }
go
func (s *Section) HasKey(name string) bool { key, _ := s.GetKey(name) return key != nil }
[ "func", "(", "s", "*", "Section", ")", "HasKey", "(", "name", "string", ")", "bool", "{", "key", ",", "_", ":=", "s", ".", "GetKey", "(", "name", ")", "\n", "return", "key", "!=", "nil", "\n", "}" ]
// HasKey returns true if section contains a key with given name.
[ "HasKey", "returns", "true", "if", "section", "contains", "a", "key", "with", "given", "name", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L140-L143
146,716
go-ini/ini
section.go
HasValue
func (s *Section) HasValue(value string) bool { if s.f.BlockMode { s.f.lock.RLock() defer s.f.lock.RUnlock() } for _, k := range s.keys { if value == k.value { return true } } return false }
go
func (s *Section) HasValue(value string) bool { if s.f.BlockMode { s.f.lock.RLock() defer s.f.lock.RUnlock() } for _, k := range s.keys { if value == k.value { return true } } return false }
[ "func", "(", "s", "*", "Section", ")", "HasValue", "(", "value", "string", ")", "bool", "{", "if", "s", ".", "f", ".", "BlockMode", "{", "s", ".", "f", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "f", ".", "lock", ".", "RUnlock", "(", ")", "\n", "}", "\n\n", "for", "_", ",", "k", ":=", "range", "s", ".", "keys", "{", "if", "value", "==", "k", ".", "value", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasValue returns true if section contains given raw value.
[ "HasValue", "returns", "true", "if", "section", "contains", "given", "raw", "value", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L151-L163
146,717
go-ini/ini
section.go
Key
func (s *Section) Key(name string) *Key { key, err := s.GetKey(name) if err != nil { // It's OK here because the only possible error is empty key name, // but if it's empty, this piece of code won't be executed. key, _ = s.NewKey(name, "") return key } return key }
go
func (s *Section) Key(name string) *Key { key, err := s.GetKey(name) if err != nil { // It's OK here because the only possible error is empty key name, // but if it's empty, this piece of code won't be executed. key, _ = s.NewKey(name, "") return key } return key }
[ "func", "(", "s", "*", "Section", ")", "Key", "(", "name", "string", ")", "*", "Key", "{", "key", ",", "err", ":=", "s", ".", "GetKey", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "// It's OK here because the only possible error is empty key name,", "// but if it's empty, this piece of code won't be executed.", "key", ",", "_", "=", "s", ".", "NewKey", "(", "name", ",", "\"", "\"", ")", "\n", "return", "key", "\n", "}", "\n", "return", "key", "\n", "}" ]
// Key assumes named Key exists in section and returns a zero-value when not.
[ "Key", "assumes", "named", "Key", "exists", "in", "section", "and", "returns", "a", "zero", "-", "value", "when", "not", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L166-L175
146,718
go-ini/ini
section.go
Keys
func (s *Section) Keys() []*Key { keys := make([]*Key, len(s.keyList)) for i := range s.keyList { keys[i] = s.Key(s.keyList[i]) } return keys }
go
func (s *Section) Keys() []*Key { keys := make([]*Key, len(s.keyList)) for i := range s.keyList { keys[i] = s.Key(s.keyList[i]) } return keys }
[ "func", "(", "s", "*", "Section", ")", "Keys", "(", ")", "[", "]", "*", "Key", "{", "keys", ":=", "make", "(", "[", "]", "*", "Key", ",", "len", "(", "s", ".", "keyList", ")", ")", "\n", "for", "i", ":=", "range", "s", ".", "keyList", "{", "keys", "[", "i", "]", "=", "s", ".", "Key", "(", "s", ".", "keyList", "[", "i", "]", ")", "\n", "}", "\n", "return", "keys", "\n", "}" ]
// Keys returns list of keys of section.
[ "Keys", "returns", "list", "of", "keys", "of", "section", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L178-L184
146,719
go-ini/ini
section.go
ParentKeys
func (s *Section) ParentKeys() []*Key { var parentKeys []*Key sname := s.name for { if i := strings.LastIndex(sname, "."); i > -1 { sname = sname[:i] sec, err := s.f.GetSection(sname) if err != nil { continue } parentKeys = append(parentKeys, sec.Keys()...) } else { break } } return parentKeys }
go
func (s *Section) ParentKeys() []*Key { var parentKeys []*Key sname := s.name for { if i := strings.LastIndex(sname, "."); i > -1 { sname = sname[:i] sec, err := s.f.GetSection(sname) if err != nil { continue } parentKeys = append(parentKeys, sec.Keys()...) } else { break } } return parentKeys }
[ "func", "(", "s", "*", "Section", ")", "ParentKeys", "(", ")", "[", "]", "*", "Key", "{", "var", "parentKeys", "[", "]", "*", "Key", "\n", "sname", ":=", "s", ".", "name", "\n", "for", "{", "if", "i", ":=", "strings", ".", "LastIndex", "(", "sname", ",", "\"", "\"", ")", ";", "i", ">", "-", "1", "{", "sname", "=", "sname", "[", ":", "i", "]", "\n", "sec", ",", "err", ":=", "s", ".", "f", ".", "GetSection", "(", "sname", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "parentKeys", "=", "append", "(", "parentKeys", ",", "sec", ".", "Keys", "(", ")", "...", ")", "\n", "}", "else", "{", "break", "\n", "}", "\n\n", "}", "\n", "return", "parentKeys", "\n", "}" ]
// ParentKeys returns list of keys of parent section.
[ "ParentKeys", "returns", "list", "of", "keys", "of", "parent", "section", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L187-L204
146,720
go-ini/ini
section.go
KeyStrings
func (s *Section) KeyStrings() []string { list := make([]string, len(s.keyList)) copy(list, s.keyList) return list }
go
func (s *Section) KeyStrings() []string { list := make([]string, len(s.keyList)) copy(list, s.keyList) return list }
[ "func", "(", "s", "*", "Section", ")", "KeyStrings", "(", ")", "[", "]", "string", "{", "list", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "s", ".", "keyList", ")", ")", "\n", "copy", "(", "list", ",", "s", ".", "keyList", ")", "\n", "return", "list", "\n", "}" ]
// KeyStrings returns list of key names of section.
[ "KeyStrings", "returns", "list", "of", "key", "names", "of", "section", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L207-L211
146,721
go-ini/ini
section.go
KeysHash
func (s *Section) KeysHash() map[string]string { if s.f.BlockMode { s.f.lock.RLock() defer s.f.lock.RUnlock() } hash := map[string]string{} for key, value := range s.keysHash { hash[key] = value } return hash }
go
func (s *Section) KeysHash() map[string]string { if s.f.BlockMode { s.f.lock.RLock() defer s.f.lock.RUnlock() } hash := map[string]string{} for key, value := range s.keysHash { hash[key] = value } return hash }
[ "func", "(", "s", "*", "Section", ")", "KeysHash", "(", ")", "map", "[", "string", "]", "string", "{", "if", "s", ".", "f", ".", "BlockMode", "{", "s", ".", "f", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "f", ".", "lock", ".", "RUnlock", "(", ")", "\n", "}", "\n\n", "hash", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "key", ",", "value", ":=", "range", "s", ".", "keysHash", "{", "hash", "[", "key", "]", "=", "value", "\n", "}", "\n", "return", "hash", "\n", "}" ]
// KeysHash returns keys hash consisting of names and values.
[ "KeysHash", "returns", "keys", "hash", "consisting", "of", "names", "and", "values", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L214-L225
146,722
go-ini/ini
section.go
DeleteKey
func (s *Section) DeleteKey(name string) { if s.f.BlockMode { s.f.lock.Lock() defer s.f.lock.Unlock() } for i, k := range s.keyList { if k == name { s.keyList = append(s.keyList[:i], s.keyList[i+1:]...) delete(s.keys, name) delete(s.keysHash, name) return } } }
go
func (s *Section) DeleteKey(name string) { if s.f.BlockMode { s.f.lock.Lock() defer s.f.lock.Unlock() } for i, k := range s.keyList { if k == name { s.keyList = append(s.keyList[:i], s.keyList[i+1:]...) delete(s.keys, name) delete(s.keysHash, name) return } } }
[ "func", "(", "s", "*", "Section", ")", "DeleteKey", "(", "name", "string", ")", "{", "if", "s", ".", "f", ".", "BlockMode", "{", "s", ".", "f", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "f", ".", "lock", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "for", "i", ",", "k", ":=", "range", "s", ".", "keyList", "{", "if", "k", "==", "name", "{", "s", ".", "keyList", "=", "append", "(", "s", ".", "keyList", "[", ":", "i", "]", ",", "s", ".", "keyList", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "delete", "(", "s", ".", "keys", ",", "name", ")", "\n", "delete", "(", "s", ".", "keysHash", ",", "name", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// DeleteKey deletes a key from section.
[ "DeleteKey", "deletes", "a", "key", "from", "section", "." ]
3be5ad479f69d4e08d7fe25edf79bf3346bd658e
https://github.com/go-ini/ini/blob/3be5ad479f69d4e08d7fe25edf79bf3346bd658e/section.go#L228-L242
146,723
emicklei/go-restful
curly.go
selectRoutes
func (c CurlyRouter) selectRoutes(ws *WebService, requestTokens []string) sortableCurlyRoutes { candidates := make(sortableCurlyRoutes, 0, 8) for _, each := range ws.routes { matches, paramCount, staticCount := c.matchesRouteByPathTokens(each.pathParts, requestTokens) if matches { candidates.add(curlyRoute{each, paramCount, staticCount}) // TODO make sure Routes() return pointers? } } sort.Sort(candidates) return candidates }
go
func (c CurlyRouter) selectRoutes(ws *WebService, requestTokens []string) sortableCurlyRoutes { candidates := make(sortableCurlyRoutes, 0, 8) for _, each := range ws.routes { matches, paramCount, staticCount := c.matchesRouteByPathTokens(each.pathParts, requestTokens) if matches { candidates.add(curlyRoute{each, paramCount, staticCount}) // TODO make sure Routes() return pointers? } } sort.Sort(candidates) return candidates }
[ "func", "(", "c", "CurlyRouter", ")", "selectRoutes", "(", "ws", "*", "WebService", ",", "requestTokens", "[", "]", "string", ")", "sortableCurlyRoutes", "{", "candidates", ":=", "make", "(", "sortableCurlyRoutes", ",", "0", ",", "8", ")", "\n", "for", "_", ",", "each", ":=", "range", "ws", ".", "routes", "{", "matches", ",", "paramCount", ",", "staticCount", ":=", "c", ".", "matchesRouteByPathTokens", "(", "each", ".", "pathParts", ",", "requestTokens", ")", "\n", "if", "matches", "{", "candidates", ".", "add", "(", "curlyRoute", "{", "each", ",", "paramCount", ",", "staticCount", "}", ")", "// TODO make sure Routes() return pointers?", "\n", "}", "\n", "}", "\n", "sort", ".", "Sort", "(", "candidates", ")", "\n", "return", "candidates", "\n", "}" ]
// selectRoutes return a collection of Route from a WebService that matches the path tokens from the request.
[ "selectRoutes", "return", "a", "collection", "of", "Route", "from", "a", "WebService", "that", "matches", "the", "path", "tokens", "from", "the", "request", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/curly.go#L47-L57
146,724
emicklei/go-restful
curly.go
matchesRouteByPathTokens
func (c CurlyRouter) matchesRouteByPathTokens(routeTokens, requestTokens []string) (matches bool, paramCount int, staticCount int) { if len(routeTokens) < len(requestTokens) { // proceed in matching only if last routeToken is wildcard count := len(routeTokens) if count == 0 || !strings.HasSuffix(routeTokens[count-1], "*}") { return false, 0, 0 } // proceed } for i, routeToken := range routeTokens { if i == len(requestTokens) { // reached end of request path return false, 0, 0 } requestToken := requestTokens[i] if strings.HasPrefix(routeToken, "{") { paramCount++ if colon := strings.Index(routeToken, ":"); colon != -1 { // match by regex matchesToken, matchesRemainder := c.regularMatchesPathToken(routeToken, colon, requestToken) if !matchesToken { return false, 0, 0 } if matchesRemainder { break } } } else { // no { prefix if requestToken != routeToken { return false, 0, 0 } staticCount++ } } return true, paramCount, staticCount }
go
func (c CurlyRouter) matchesRouteByPathTokens(routeTokens, requestTokens []string) (matches bool, paramCount int, staticCount int) { if len(routeTokens) < len(requestTokens) { // proceed in matching only if last routeToken is wildcard count := len(routeTokens) if count == 0 || !strings.HasSuffix(routeTokens[count-1], "*}") { return false, 0, 0 } // proceed } for i, routeToken := range routeTokens { if i == len(requestTokens) { // reached end of request path return false, 0, 0 } requestToken := requestTokens[i] if strings.HasPrefix(routeToken, "{") { paramCount++ if colon := strings.Index(routeToken, ":"); colon != -1 { // match by regex matchesToken, matchesRemainder := c.regularMatchesPathToken(routeToken, colon, requestToken) if !matchesToken { return false, 0, 0 } if matchesRemainder { break } } } else { // no { prefix if requestToken != routeToken { return false, 0, 0 } staticCount++ } } return true, paramCount, staticCount }
[ "func", "(", "c", "CurlyRouter", ")", "matchesRouteByPathTokens", "(", "routeTokens", ",", "requestTokens", "[", "]", "string", ")", "(", "matches", "bool", ",", "paramCount", "int", ",", "staticCount", "int", ")", "{", "if", "len", "(", "routeTokens", ")", "<", "len", "(", "requestTokens", ")", "{", "// proceed in matching only if last routeToken is wildcard", "count", ":=", "len", "(", "routeTokens", ")", "\n", "if", "count", "==", "0", "||", "!", "strings", ".", "HasSuffix", "(", "routeTokens", "[", "count", "-", "1", "]", ",", "\"", "\"", ")", "{", "return", "false", ",", "0", ",", "0", "\n", "}", "\n", "// proceed", "}", "\n", "for", "i", ",", "routeToken", ":=", "range", "routeTokens", "{", "if", "i", "==", "len", "(", "requestTokens", ")", "{", "// reached end of request path", "return", "false", ",", "0", ",", "0", "\n", "}", "\n", "requestToken", ":=", "requestTokens", "[", "i", "]", "\n", "if", "strings", ".", "HasPrefix", "(", "routeToken", ",", "\"", "\"", ")", "{", "paramCount", "++", "\n", "if", "colon", ":=", "strings", ".", "Index", "(", "routeToken", ",", "\"", "\"", ")", ";", "colon", "!=", "-", "1", "{", "// match by regex", "matchesToken", ",", "matchesRemainder", ":=", "c", ".", "regularMatchesPathToken", "(", "routeToken", ",", "colon", ",", "requestToken", ")", "\n", "if", "!", "matchesToken", "{", "return", "false", ",", "0", ",", "0", "\n", "}", "\n", "if", "matchesRemainder", "{", "break", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// no { prefix", "if", "requestToken", "!=", "routeToken", "{", "return", "false", ",", "0", ",", "0", "\n", "}", "\n", "staticCount", "++", "\n", "}", "\n", "}", "\n", "return", "true", ",", "paramCount", ",", "staticCount", "\n", "}" ]
// matchesRouteByPathTokens computes whether it matches, howmany parameters do match and what the number of static path elements are.
[ "matchesRouteByPathTokens", "computes", "whether", "it", "matches", "howmany", "parameters", "do", "match", "and", "what", "the", "number", "of", "static", "path", "elements", "are", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/curly.go#L60-L95
146,725
emicklei/go-restful
curly.go
detectRoute
func (c CurlyRouter) detectRoute(candidateRoutes sortableCurlyRoutes, httpRequest *http.Request) (*Route, error) { // tracing is done inside detectRoute return jsr311Router.detectRoute(candidateRoutes.routes(), httpRequest) }
go
func (c CurlyRouter) detectRoute(candidateRoutes sortableCurlyRoutes, httpRequest *http.Request) (*Route, error) { // tracing is done inside detectRoute return jsr311Router.detectRoute(candidateRoutes.routes(), httpRequest) }
[ "func", "(", "c", "CurlyRouter", ")", "detectRoute", "(", "candidateRoutes", "sortableCurlyRoutes", ",", "httpRequest", "*", "http", ".", "Request", ")", "(", "*", "Route", ",", "error", ")", "{", "// tracing is done inside detectRoute", "return", "jsr311Router", ".", "detectRoute", "(", "candidateRoutes", ".", "routes", "(", ")", ",", "httpRequest", ")", "\n", "}" ]
// detectRoute selectes from a list of Route the first match by inspecting both the Accept and Content-Type // headers of the Request. See also RouterJSR311 in jsr311.go
[ "detectRoute", "selectes", "from", "a", "list", "of", "Route", "the", "first", "match", "by", "inspecting", "both", "the", "Accept", "and", "Content", "-", "Type", "headers", "of", "the", "Request", ".", "See", "also", "RouterJSR311", "in", "jsr311", ".", "go" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/curly.go#L115-L118
146,726
emicklei/go-restful
curly.go
detectWebService
func (c CurlyRouter) detectWebService(requestTokens []string, webServices []*WebService) *WebService { var best *WebService score := -1 for _, each := range webServices { matches, eachScore := c.computeWebserviceScore(requestTokens, each.pathExpr.tokens) if matches && (eachScore > score) { best = each score = eachScore } } return best }
go
func (c CurlyRouter) detectWebService(requestTokens []string, webServices []*WebService) *WebService { var best *WebService score := -1 for _, each := range webServices { matches, eachScore := c.computeWebserviceScore(requestTokens, each.pathExpr.tokens) if matches && (eachScore > score) { best = each score = eachScore } } return best }
[ "func", "(", "c", "CurlyRouter", ")", "detectWebService", "(", "requestTokens", "[", "]", "string", ",", "webServices", "[", "]", "*", "WebService", ")", "*", "WebService", "{", "var", "best", "*", "WebService", "\n", "score", ":=", "-", "1", "\n", "for", "_", ",", "each", ":=", "range", "webServices", "{", "matches", ",", "eachScore", ":=", "c", ".", "computeWebserviceScore", "(", "requestTokens", ",", "each", ".", "pathExpr", ".", "tokens", ")", "\n", "if", "matches", "&&", "(", "eachScore", ">", "score", ")", "{", "best", "=", "each", "\n", "score", "=", "eachScore", "\n", "}", "\n", "}", "\n", "return", "best", "\n", "}" ]
// detectWebService returns the best matching webService given the list of path tokens. // see also computeWebserviceScore
[ "detectWebService", "returns", "the", "best", "matching", "webService", "given", "the", "list", "of", "path", "tokens", ".", "see", "also", "computeWebserviceScore" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/curly.go#L122-L133
146,727
emicklei/go-restful
curly.go
computeWebserviceScore
func (c CurlyRouter) computeWebserviceScore(requestTokens []string, tokens []string) (bool, int) { if len(tokens) > len(requestTokens) { return false, 0 } score := 0 for i := 0; i < len(tokens); i++ { each := requestTokens[i] other := tokens[i] if len(each) == 0 && len(other) == 0 { score++ continue } if len(other) > 0 && strings.HasPrefix(other, "{") { // no empty match if len(each) == 0 { return false, score } score += 1 } else { // not a parameter if each != other { return false, score } score += (len(tokens) - i) * 10 //fuzzy } } return true, score }
go
func (c CurlyRouter) computeWebserviceScore(requestTokens []string, tokens []string) (bool, int) { if len(tokens) > len(requestTokens) { return false, 0 } score := 0 for i := 0; i < len(tokens); i++ { each := requestTokens[i] other := tokens[i] if len(each) == 0 && len(other) == 0 { score++ continue } if len(other) > 0 && strings.HasPrefix(other, "{") { // no empty match if len(each) == 0 { return false, score } score += 1 } else { // not a parameter if each != other { return false, score } score += (len(tokens) - i) * 10 //fuzzy } } return true, score }
[ "func", "(", "c", "CurlyRouter", ")", "computeWebserviceScore", "(", "requestTokens", "[", "]", "string", ",", "tokens", "[", "]", "string", ")", "(", "bool", ",", "int", ")", "{", "if", "len", "(", "tokens", ")", ">", "len", "(", "requestTokens", ")", "{", "return", "false", ",", "0", "\n", "}", "\n", "score", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "tokens", ")", ";", "i", "++", "{", "each", ":=", "requestTokens", "[", "i", "]", "\n", "other", ":=", "tokens", "[", "i", "]", "\n", "if", "len", "(", "each", ")", "==", "0", "&&", "len", "(", "other", ")", "==", "0", "{", "score", "++", "\n", "continue", "\n", "}", "\n", "if", "len", "(", "other", ")", ">", "0", "&&", "strings", ".", "HasPrefix", "(", "other", ",", "\"", "\"", ")", "{", "// no empty match", "if", "len", "(", "each", ")", "==", "0", "{", "return", "false", ",", "score", "\n", "}", "\n", "score", "+=", "1", "\n", "}", "else", "{", "// not a parameter", "if", "each", "!=", "other", "{", "return", "false", ",", "score", "\n", "}", "\n", "score", "+=", "(", "len", "(", "tokens", ")", "-", "i", ")", "*", "10", "//fuzzy", "\n", "}", "\n", "}", "\n", "return", "true", ",", "score", "\n", "}" ]
// computeWebserviceScore returns whether tokens match and // the weighted score of the longest matching consecutive tokens from the beginning.
[ "computeWebserviceScore", "returns", "whether", "tokens", "match", "and", "the", "weighted", "score", "of", "the", "longest", "matching", "consecutive", "tokens", "from", "the", "beginning", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/curly.go#L137-L164
146,728
emicklei/go-restful
examples/restful-full-logging-filter.go
main
func main() { restful.Add(newUserService()) log.Print("start listening on localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
go
func main() { restful.Add(newUserService()) log.Print("start listening on localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
[ "func", "main", "(", ")", "{", "restful", ".", "Add", "(", "newUserService", "(", ")", ")", "\n", "log", ".", "Print", "(", "\"", "\"", ")", "\n", "log", ".", "Fatal", "(", "http", ".", "ListenAndServe", "(", "\"", "\"", ",", "nil", ")", ")", "\n", "}" ]
// // This example shows how to log both the request body and response body
[ "This", "example", "shows", "how", "to", "log", "both", "the", "request", "body", "and", "response", "body" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/examples/restful-full-logging-filter.go#L20-L24
146,729
emicklei/go-restful
route_builder.go
Method
func (b *RouteBuilder) Method(method string) *RouteBuilder { b.httpMethod = method return b }
go
func (b *RouteBuilder) Method(method string) *RouteBuilder { b.httpMethod = method return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Method", "(", "method", "string", ")", "*", "RouteBuilder", "{", "b", ".", "httpMethod", "=", "method", "\n", "return", "b", "\n", "}" ]
// Method specifies what HTTP method to match. Required.
[ "Method", "specifies", "what", "HTTP", "method", "to", "match", ".", "Required", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L67-L70
146,730
emicklei/go-restful
route_builder.go
Produces
func (b *RouteBuilder) Produces(mimeTypes ...string) *RouteBuilder { b.produces = mimeTypes return b }
go
func (b *RouteBuilder) Produces(mimeTypes ...string) *RouteBuilder { b.produces = mimeTypes return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Produces", "(", "mimeTypes", "...", "string", ")", "*", "RouteBuilder", "{", "b", ".", "produces", "=", "mimeTypes", "\n", "return", "b", "\n", "}" ]
// Produces specifies what MIME types can be produced ; the matched one will appear in the Content-Type Http header.
[ "Produces", "specifies", "what", "MIME", "types", "can", "be", "produced", ";", "the", "matched", "one", "will", "appear", "in", "the", "Content", "-", "Type", "Http", "header", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L73-L76
146,731
emicklei/go-restful
route_builder.go
Consumes
func (b *RouteBuilder) Consumes(mimeTypes ...string) *RouteBuilder { b.consumes = mimeTypes return b }
go
func (b *RouteBuilder) Consumes(mimeTypes ...string) *RouteBuilder { b.consumes = mimeTypes return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Consumes", "(", "mimeTypes", "...", "string", ")", "*", "RouteBuilder", "{", "b", ".", "consumes", "=", "mimeTypes", "\n", "return", "b", "\n", "}" ]
// Consumes specifies what MIME types can be consumes ; the Accept Http header must matched any of these
[ "Consumes", "specifies", "what", "MIME", "types", "can", "be", "consumes", ";", "the", "Accept", "Http", "header", "must", "matched", "any", "of", "these" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L79-L82
146,732
emicklei/go-restful
route_builder.go
Doc
func (b *RouteBuilder) Doc(documentation string) *RouteBuilder { b.doc = documentation return b }
go
func (b *RouteBuilder) Doc(documentation string) *RouteBuilder { b.doc = documentation return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Doc", "(", "documentation", "string", ")", "*", "RouteBuilder", "{", "b", ".", "doc", "=", "documentation", "\n", "return", "b", "\n", "}" ]
// Doc tells what this route is all about. Optional.
[ "Doc", "tells", "what", "this", "route", "is", "all", "about", ".", "Optional", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L91-L94
146,733
emicklei/go-restful
route_builder.go
Notes
func (b *RouteBuilder) Notes(notes string) *RouteBuilder { b.notes = notes return b }
go
func (b *RouteBuilder) Notes(notes string) *RouteBuilder { b.notes = notes return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Notes", "(", "notes", "string", ")", "*", "RouteBuilder", "{", "b", ".", "notes", "=", "notes", "\n", "return", "b", "\n", "}" ]
// Notes is a verbose explanation of the operation behavior. Optional.
[ "Notes", "is", "a", "verbose", "explanation", "of", "the", "operation", "behavior", ".", "Optional", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L97-L100
146,734
emicklei/go-restful
route_builder.go
Reads
func (b *RouteBuilder) Reads(sample interface{}, optionalDescription ...string) *RouteBuilder { fn := b.typeNameHandleFunc if fn == nil { fn = reflectTypeName } typeAsName := fn(sample) description := "" if len(optionalDescription) > 0 { description = optionalDescription[0] } b.readSample = sample bodyParameter := &Parameter{&ParameterData{Name: "body", Description: description}} bodyParameter.beBody() bodyParameter.Required(true) bodyParameter.DataType(typeAsName) b.Param(bodyParameter) return b }
go
func (b *RouteBuilder) Reads(sample interface{}, optionalDescription ...string) *RouteBuilder { fn := b.typeNameHandleFunc if fn == nil { fn = reflectTypeName } typeAsName := fn(sample) description := "" if len(optionalDescription) > 0 { description = optionalDescription[0] } b.readSample = sample bodyParameter := &Parameter{&ParameterData{Name: "body", Description: description}} bodyParameter.beBody() bodyParameter.Required(true) bodyParameter.DataType(typeAsName) b.Param(bodyParameter) return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Reads", "(", "sample", "interface", "{", "}", ",", "optionalDescription", "...", "string", ")", "*", "RouteBuilder", "{", "fn", ":=", "b", ".", "typeNameHandleFunc", "\n", "if", "fn", "==", "nil", "{", "fn", "=", "reflectTypeName", "\n", "}", "\n", "typeAsName", ":=", "fn", "(", "sample", ")", "\n", "description", ":=", "\"", "\"", "\n", "if", "len", "(", "optionalDescription", ")", ">", "0", "{", "description", "=", "optionalDescription", "[", "0", "]", "\n", "}", "\n", "b", ".", "readSample", "=", "sample", "\n", "bodyParameter", ":=", "&", "Parameter", "{", "&", "ParameterData", "{", "Name", ":", "\"", "\"", ",", "Description", ":", "description", "}", "}", "\n", "bodyParameter", ".", "beBody", "(", ")", "\n", "bodyParameter", ".", "Required", "(", "true", ")", "\n", "bodyParameter", ".", "DataType", "(", "typeAsName", ")", "\n", "b", ".", "Param", "(", "bodyParameter", ")", "\n", "return", "b", "\n", "}" ]
// Reads tells what resource type will be read from the request payload. Optional. // A parameter of type "body" is added ,required is set to true and the dataType is set to the qualified name of the sample's type.
[ "Reads", "tells", "what", "resource", "type", "will", "be", "read", "from", "the", "request", "payload", ".", "Optional", ".", "A", "parameter", "of", "type", "body", "is", "added", "required", "is", "set", "to", "true", "and", "the", "dataType", "is", "set", "to", "the", "qualified", "name", "of", "the", "sample", "s", "type", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L104-L121
146,735
emicklei/go-restful
route_builder.go
ReturnsError
func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder { log.Print("ReturnsError is deprecated, use Returns instead.") return b.Returns(code, message, model) }
go
func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder { log.Print("ReturnsError is deprecated, use Returns instead.") return b.Returns(code, message, model) }
[ "func", "(", "b", "*", "RouteBuilder", ")", "ReturnsError", "(", "code", "int", ",", "message", "string", ",", "model", "interface", "{", "}", ")", "*", "RouteBuilder", "{", "log", ".", "Print", "(", "\"", "\"", ")", "\n", "return", "b", ".", "Returns", "(", "code", ",", "message", ",", "model", ")", "\n", "}" ]
// ReturnsError is deprecated, use Returns instead.
[ "ReturnsError", "is", "deprecated", "use", "Returns", "instead", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L157-L160
146,736
emicklei/go-restful
route_builder.go
DefaultReturns
func (b *RouteBuilder) DefaultReturns(message string, model interface{}) *RouteBuilder { b.defaultResponse = &ResponseError{ Message: message, Model: model, } return b }
go
func (b *RouteBuilder) DefaultReturns(message string, model interface{}) *RouteBuilder { b.defaultResponse = &ResponseError{ Message: message, Model: model, } return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "DefaultReturns", "(", "message", "string", ",", "model", "interface", "{", "}", ")", "*", "RouteBuilder", "{", "b", ".", "defaultResponse", "=", "&", "ResponseError", "{", "Message", ":", "message", ",", "Model", ":", "model", ",", "}", "\n", "return", "b", "\n", "}" ]
// DefaultReturns is a special Returns call that sets the default of the response.
[ "DefaultReturns", "is", "a", "special", "Returns", "call", "that", "sets", "the", "default", "of", "the", "response", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L180-L186
146,737
emicklei/go-restful
route_builder.go
Metadata
func (b *RouteBuilder) Metadata(key string, value interface{}) *RouteBuilder { if b.metadata == nil { b.metadata = map[string]interface{}{} } b.metadata[key] = value return b }
go
func (b *RouteBuilder) Metadata(key string, value interface{}) *RouteBuilder { if b.metadata == nil { b.metadata = map[string]interface{}{} } b.metadata[key] = value return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Metadata", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "*", "RouteBuilder", "{", "if", "b", ".", "metadata", "==", "nil", "{", "b", ".", "metadata", "=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "}", "\n", "b", ".", "metadata", "[", "key", "]", "=", "value", "\n", "return", "b", "\n", "}" ]
// Metadata adds or updates a key=value pair to the metadata map.
[ "Metadata", "adds", "or", "updates", "a", "key", "=", "value", "pair", "to", "the", "metadata", "map", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L189-L195
146,738
emicklei/go-restful
route_builder.go
Filter
func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder { b.filters = append(b.filters, filter) return b }
go
func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder { b.filters = append(b.filters, filter) return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Filter", "(", "filter", "FilterFunction", ")", "*", "RouteBuilder", "{", "b", ".", "filters", "=", "append", "(", "b", ".", "filters", ",", "filter", ")", "\n", "return", "b", "\n", "}" ]
// Filter appends a FilterFunction to the end of filters for this Route to build.
[ "Filter", "appends", "a", "FilterFunction", "to", "the", "end", "of", "filters", "for", "this", "Route", "to", "build", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L217-L220
146,739
emicklei/go-restful
route_builder.go
ContentEncodingEnabled
func (b *RouteBuilder) ContentEncodingEnabled(enabled bool) *RouteBuilder { b.contentEncodingEnabled = &enabled return b }
go
func (b *RouteBuilder) ContentEncodingEnabled(enabled bool) *RouteBuilder { b.contentEncodingEnabled = &enabled return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "ContentEncodingEnabled", "(", "enabled", "bool", ")", "*", "RouteBuilder", "{", "b", ".", "contentEncodingEnabled", "=", "&", "enabled", "\n", "return", "b", "\n", "}" ]
// ContentEncodingEnabled allows you to override the Containers value for auto-compressing this route response.
[ "ContentEncodingEnabled", "allows", "you", "to", "override", "the", "Containers", "value", "for", "auto", "-", "compressing", "this", "route", "response", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L238-L241
146,740
emicklei/go-restful
route_builder.go
copyDefaults
func (b *RouteBuilder) copyDefaults(rootProduces, rootConsumes []string) { if len(b.produces) == 0 { b.produces = rootProduces } if len(b.consumes) == 0 { b.consumes = rootConsumes } }
go
func (b *RouteBuilder) copyDefaults(rootProduces, rootConsumes []string) { if len(b.produces) == 0 { b.produces = rootProduces } if len(b.consumes) == 0 { b.consumes = rootConsumes } }
[ "func", "(", "b", "*", "RouteBuilder", ")", "copyDefaults", "(", "rootProduces", ",", "rootConsumes", "[", "]", "string", ")", "{", "if", "len", "(", "b", ".", "produces", ")", "==", "0", "{", "b", ".", "produces", "=", "rootProduces", "\n", "}", "\n", "if", "len", "(", "b", ".", "consumes", ")", "==", "0", "{", "b", ".", "consumes", "=", "rootConsumes", "\n", "}", "\n", "}" ]
// If no specific Route path then set to rootPath // If no specific Produces then set to rootProduces // If no specific Consumes then set to rootConsumes
[ "If", "no", "specific", "Route", "path", "then", "set", "to", "rootPath", "If", "no", "specific", "Produces", "then", "set", "to", "rootProduces", "If", "no", "specific", "Consumes", "then", "set", "to", "rootConsumes" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L246-L253
146,741
emicklei/go-restful
route_builder.go
typeNameHandler
func (b *RouteBuilder) typeNameHandler(handler TypeNameHandleFunction) *RouteBuilder { b.typeNameHandleFunc = handler return b }
go
func (b *RouteBuilder) typeNameHandler(handler TypeNameHandleFunction) *RouteBuilder { b.typeNameHandleFunc = handler return b }
[ "func", "(", "b", "*", "RouteBuilder", ")", "typeNameHandler", "(", "handler", "TypeNameHandleFunction", ")", "*", "RouteBuilder", "{", "b", ".", "typeNameHandleFunc", "=", "handler", "\n", "return", "b", "\n", "}" ]
// typeNameHandler sets the function that will convert types to strings in the parameter // and model definitions.
[ "typeNameHandler", "sets", "the", "function", "that", "will", "convert", "types", "to", "strings", "in", "the", "parameter", "and", "model", "definitions", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L257-L260
146,742
emicklei/go-restful
route_builder.go
Build
func (b *RouteBuilder) Build() Route { pathExpr, err := newPathExpression(b.currentPath) if err != nil { log.Printf("Invalid path:%s because:%v", b.currentPath, err) os.Exit(1) } if b.function == nil { log.Printf("No function specified for route:" + b.currentPath) os.Exit(1) } operationName := b.operation if len(operationName) == 0 && b.function != nil { // extract from definition operationName = nameOfFunction(b.function) } route := Route{ Method: b.httpMethod, Path: concatPath(b.rootPath, b.currentPath), Produces: b.produces, Consumes: b.consumes, Function: b.function, Filters: b.filters, If: b.conditions, relativePath: b.currentPath, pathExpr: pathExpr, Doc: b.doc, Notes: b.notes, Operation: operationName, ParameterDocs: b.parameters, ResponseErrors: b.errorMap, DefaultResponse: b.defaultResponse, ReadSample: b.readSample, WriteSample: b.writeSample, Metadata: b.metadata, Deprecated: b.deprecated, contentEncodingEnabled: b.contentEncodingEnabled, } route.postBuild() return route }
go
func (b *RouteBuilder) Build() Route { pathExpr, err := newPathExpression(b.currentPath) if err != nil { log.Printf("Invalid path:%s because:%v", b.currentPath, err) os.Exit(1) } if b.function == nil { log.Printf("No function specified for route:" + b.currentPath) os.Exit(1) } operationName := b.operation if len(operationName) == 0 && b.function != nil { // extract from definition operationName = nameOfFunction(b.function) } route := Route{ Method: b.httpMethod, Path: concatPath(b.rootPath, b.currentPath), Produces: b.produces, Consumes: b.consumes, Function: b.function, Filters: b.filters, If: b.conditions, relativePath: b.currentPath, pathExpr: pathExpr, Doc: b.doc, Notes: b.notes, Operation: operationName, ParameterDocs: b.parameters, ResponseErrors: b.errorMap, DefaultResponse: b.defaultResponse, ReadSample: b.readSample, WriteSample: b.writeSample, Metadata: b.metadata, Deprecated: b.deprecated, contentEncodingEnabled: b.contentEncodingEnabled, } route.postBuild() return route }
[ "func", "(", "b", "*", "RouteBuilder", ")", "Build", "(", ")", "Route", "{", "pathExpr", ",", "err", ":=", "newPathExpression", "(", "b", ".", "currentPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "b", ".", "currentPath", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "if", "b", ".", "function", "==", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", "+", "b", ".", "currentPath", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "operationName", ":=", "b", ".", "operation", "\n", "if", "len", "(", "operationName", ")", "==", "0", "&&", "b", ".", "function", "!=", "nil", "{", "// extract from definition", "operationName", "=", "nameOfFunction", "(", "b", ".", "function", ")", "\n", "}", "\n", "route", ":=", "Route", "{", "Method", ":", "b", ".", "httpMethod", ",", "Path", ":", "concatPath", "(", "b", ".", "rootPath", ",", "b", ".", "currentPath", ")", ",", "Produces", ":", "b", ".", "produces", ",", "Consumes", ":", "b", ".", "consumes", ",", "Function", ":", "b", ".", "function", ",", "Filters", ":", "b", ".", "filters", ",", "If", ":", "b", ".", "conditions", ",", "relativePath", ":", "b", ".", "currentPath", ",", "pathExpr", ":", "pathExpr", ",", "Doc", ":", "b", ".", "doc", ",", "Notes", ":", "b", ".", "notes", ",", "Operation", ":", "operationName", ",", "ParameterDocs", ":", "b", ".", "parameters", ",", "ResponseErrors", ":", "b", ".", "errorMap", ",", "DefaultResponse", ":", "b", ".", "defaultResponse", ",", "ReadSample", ":", "b", ".", "readSample", ",", "WriteSample", ":", "b", ".", "writeSample", ",", "Metadata", ":", "b", ".", "metadata", ",", "Deprecated", ":", "b", ".", "deprecated", ",", "contentEncodingEnabled", ":", "b", ".", "contentEncodingEnabled", ",", "}", "\n", "route", ".", "postBuild", "(", ")", "\n", "return", "route", "\n", "}" ]
// Build creates a new Route using the specification details collected by the RouteBuilder
[ "Build", "creates", "a", "new", "Route", "using", "the", "specification", "details", "collected", "by", "the", "RouteBuilder" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L263-L302
146,743
emicklei/go-restful
route_builder.go
nameOfFunction
func nameOfFunction(f interface{}) string { fun := runtime.FuncForPC(reflect.ValueOf(f).Pointer()) tokenized := strings.Split(fun.Name(), ".") last := tokenized[len(tokenized)-1] last = strings.TrimSuffix(last, ")·fm") // < Go 1.5 last = strings.TrimSuffix(last, ")-fm") // Go 1.5 last = strings.TrimSuffix(last, "·fm") // < Go 1.5 last = strings.TrimSuffix(last, "-fm") // Go 1.5 if last == "func1" { // this could mean conflicts in API docs val := atomic.AddInt32(&anonymousFuncCount, 1) last = "func" + fmt.Sprintf("%d", val) atomic.StoreInt32(&anonymousFuncCount, val) } return last }
go
func nameOfFunction(f interface{}) string { fun := runtime.FuncForPC(reflect.ValueOf(f).Pointer()) tokenized := strings.Split(fun.Name(), ".") last := tokenized[len(tokenized)-1] last = strings.TrimSuffix(last, ")·fm") // < Go 1.5 last = strings.TrimSuffix(last, ")-fm") // Go 1.5 last = strings.TrimSuffix(last, "·fm") // < Go 1.5 last = strings.TrimSuffix(last, "-fm") // Go 1.5 if last == "func1" { // this could mean conflicts in API docs val := atomic.AddInt32(&anonymousFuncCount, 1) last = "func" + fmt.Sprintf("%d", val) atomic.StoreInt32(&anonymousFuncCount, val) } return last }
[ "func", "nameOfFunction", "(", "f", "interface", "{", "}", ")", "string", "{", "fun", ":=", "runtime", ".", "FuncForPC", "(", "reflect", ".", "ValueOf", "(", "f", ")", ".", "Pointer", "(", ")", ")", "\n", "tokenized", ":=", "strings", ".", "Split", "(", "fun", ".", "Name", "(", ")", ",", "\"", "\"", ")", "\n", "last", ":=", "tokenized", "[", "len", "(", "tokenized", ")", "-", "1", "]", "\n", "last", "=", "strings", ".", "TrimSuffix", "(", "last", ",", "\"", ")", " ", "/ < Go 1.5", "\n", "last", "=", "strings", ".", "TrimSuffix", "(", "last", ",", "\"", "\"", ")", "// Go 1.5", "\n", "last", "=", "strings", ".", "TrimSuffix", "(", "last", ",", "\"", ")", " ", "/ < Go 1.5", "\n", "last", "=", "strings", ".", "TrimSuffix", "(", "last", ",", "\"", "\"", ")", "// Go 1.5", "\n", "if", "last", "==", "\"", "\"", "{", "// this could mean conflicts in API docs", "val", ":=", "atomic", ".", "AddInt32", "(", "&", "anonymousFuncCount", ",", "1", ")", "\n", "last", "=", "\"", "\"", "+", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "val", ")", "\n", "atomic", ".", "StoreInt32", "(", "&", "anonymousFuncCount", ",", "val", ")", "\n", "}", "\n", "return", "last", "\n", "}" ]
// nameOfFunction returns the short name of the function f for documentation. // It uses a runtime feature for debugging ; its value may change for later Go versions.
[ "nameOfFunction", "returns", "the", "short", "name", "of", "the", "function", "f", "for", "documentation", ".", "It", "uses", "a", "runtime", "feature", "for", "debugging", ";", "its", "value", "may", "change", "for", "later", "Go", "versions", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route_builder.go#L312-L326
146,744
emicklei/go-restful
path_expression.go
newPathExpression
func newPathExpression(path string) (*pathExpression, error) { expression, literalCount, varNames, varCount, tokens := templateToRegularExpression(path) compiled, err := regexp.Compile(expression) if err != nil { return nil, err } return &pathExpression{literalCount, varNames, varCount, compiled, expression, tokens}, nil }
go
func newPathExpression(path string) (*pathExpression, error) { expression, literalCount, varNames, varCount, tokens := templateToRegularExpression(path) compiled, err := regexp.Compile(expression) if err != nil { return nil, err } return &pathExpression{literalCount, varNames, varCount, compiled, expression, tokens}, nil }
[ "func", "newPathExpression", "(", "path", "string", ")", "(", "*", "pathExpression", ",", "error", ")", "{", "expression", ",", "literalCount", ",", "varNames", ",", "varCount", ",", "tokens", ":=", "templateToRegularExpression", "(", "path", ")", "\n", "compiled", ",", "err", ":=", "regexp", ".", "Compile", "(", "expression", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "pathExpression", "{", "literalCount", ",", "varNames", ",", "varCount", ",", "compiled", ",", "expression", ",", "tokens", "}", ",", "nil", "\n", "}" ]
// NewPathExpression creates a PathExpression from the input URL path. // Returns an error if the path is invalid.
[ "NewPathExpression", "creates", "a", "PathExpression", "from", "the", "input", "URL", "path", ".", "Returns", "an", "error", "if", "the", "path", "is", "invalid", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/path_expression.go#L27-L34
146,745
emicklei/go-restful
request.go
QueryParameters
func (r *Request) QueryParameters(name string) []string { return r.Request.URL.Query()[name] }
go
func (r *Request) QueryParameters(name string) []string { return r.Request.URL.Query()[name] }
[ "func", "(", "r", "*", "Request", ")", "QueryParameters", "(", "name", "string", ")", "[", "]", "string", "{", "return", "r", ".", "Request", ".", "URL", ".", "Query", "(", ")", "[", "name", "]", "\n", "}" ]
// QueryParameters returns the all the query parameters values by name
[ "QueryParameters", "returns", "the", "all", "the", "query", "parameters", "values", "by", "name" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/request.go#L55-L57
146,746
emicklei/go-restful
request.go
HeaderParameter
func (r *Request) HeaderParameter(name string) string { return r.Request.Header.Get(name) }
go
func (r *Request) HeaderParameter(name string) string { return r.Request.Header.Get(name) }
[ "func", "(", "r", "*", "Request", ")", "HeaderParameter", "(", "name", "string", ")", "string", "{", "return", "r", ".", "Request", ".", "Header", ".", "Get", "(", "name", ")", "\n", "}" ]
// HeaderParameter returns the HTTP Header value of a Header name or empty if missing
[ "HeaderParameter", "returns", "the", "HTTP", "Header", "value", "of", "a", "Header", "name", "or", "empty", "if", "missing" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/request.go#L69-L71
146,747
emicklei/go-restful
request.go
ReadEntity
func (r *Request) ReadEntity(entityPointer interface{}) (err error) { contentType := r.Request.Header.Get(HEADER_ContentType) contentEncoding := r.Request.Header.Get(HEADER_ContentEncoding) // check if the request body needs decompression if ENCODING_GZIP == contentEncoding { gzipReader := currentCompressorProvider.AcquireGzipReader() defer currentCompressorProvider.ReleaseGzipReader(gzipReader) gzipReader.Reset(r.Request.Body) r.Request.Body = gzipReader } else if ENCODING_DEFLATE == contentEncoding { zlibReader, err := zlib.NewReader(r.Request.Body) if err != nil { return err } r.Request.Body = zlibReader } // lookup the EntityReader, use defaultRequestContentType if needed and provided entityReader, ok := entityAccessRegistry.accessorAt(contentType) if !ok { if len(defaultRequestContentType) != 0 { entityReader, ok = entityAccessRegistry.accessorAt(defaultRequestContentType) } if !ok { return NewError(http.StatusBadRequest, "Unable to unmarshal content of type:"+contentType) } } return entityReader.Read(r, entityPointer) }
go
func (r *Request) ReadEntity(entityPointer interface{}) (err error) { contentType := r.Request.Header.Get(HEADER_ContentType) contentEncoding := r.Request.Header.Get(HEADER_ContentEncoding) // check if the request body needs decompression if ENCODING_GZIP == contentEncoding { gzipReader := currentCompressorProvider.AcquireGzipReader() defer currentCompressorProvider.ReleaseGzipReader(gzipReader) gzipReader.Reset(r.Request.Body) r.Request.Body = gzipReader } else if ENCODING_DEFLATE == contentEncoding { zlibReader, err := zlib.NewReader(r.Request.Body) if err != nil { return err } r.Request.Body = zlibReader } // lookup the EntityReader, use defaultRequestContentType if needed and provided entityReader, ok := entityAccessRegistry.accessorAt(contentType) if !ok { if len(defaultRequestContentType) != 0 { entityReader, ok = entityAccessRegistry.accessorAt(defaultRequestContentType) } if !ok { return NewError(http.StatusBadRequest, "Unable to unmarshal content of type:"+contentType) } } return entityReader.Read(r, entityPointer) }
[ "func", "(", "r", "*", "Request", ")", "ReadEntity", "(", "entityPointer", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "contentType", ":=", "r", ".", "Request", ".", "Header", ".", "Get", "(", "HEADER_ContentType", ")", "\n", "contentEncoding", ":=", "r", ".", "Request", ".", "Header", ".", "Get", "(", "HEADER_ContentEncoding", ")", "\n\n", "// check if the request body needs decompression", "if", "ENCODING_GZIP", "==", "contentEncoding", "{", "gzipReader", ":=", "currentCompressorProvider", ".", "AcquireGzipReader", "(", ")", "\n", "defer", "currentCompressorProvider", ".", "ReleaseGzipReader", "(", "gzipReader", ")", "\n", "gzipReader", ".", "Reset", "(", "r", ".", "Request", ".", "Body", ")", "\n", "r", ".", "Request", ".", "Body", "=", "gzipReader", "\n", "}", "else", "if", "ENCODING_DEFLATE", "==", "contentEncoding", "{", "zlibReader", ",", "err", ":=", "zlib", ".", "NewReader", "(", "r", ".", "Request", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "r", ".", "Request", ".", "Body", "=", "zlibReader", "\n", "}", "\n\n", "// lookup the EntityReader, use defaultRequestContentType if needed and provided", "entityReader", ",", "ok", ":=", "entityAccessRegistry", ".", "accessorAt", "(", "contentType", ")", "\n", "if", "!", "ok", "{", "if", "len", "(", "defaultRequestContentType", ")", "!=", "0", "{", "entityReader", ",", "ok", "=", "entityAccessRegistry", ".", "accessorAt", "(", "defaultRequestContentType", ")", "\n", "}", "\n", "if", "!", "ok", "{", "return", "NewError", "(", "http", ".", "StatusBadRequest", ",", "\"", "\"", "+", "contentType", ")", "\n", "}", "\n", "}", "\n", "return", "entityReader", ".", "Read", "(", "r", ",", "entityPointer", ")", "\n", "}" ]
// ReadEntity checks the Accept header and reads the content into the entityPointer.
[ "ReadEntity", "checks", "the", "Accept", "header", "and", "reads", "the", "content", "into", "the", "entityPointer", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/request.go#L74-L103
146,748
emicklei/go-restful
request.go
SetAttribute
func (r *Request) SetAttribute(name string, value interface{}) { r.attributes[name] = value }
go
func (r *Request) SetAttribute(name string, value interface{}) { r.attributes[name] = value }
[ "func", "(", "r", "*", "Request", ")", "SetAttribute", "(", "name", "string", ",", "value", "interface", "{", "}", ")", "{", "r", ".", "attributes", "[", "name", "]", "=", "value", "\n", "}" ]
// SetAttribute adds or replaces the attribute with the given value.
[ "SetAttribute", "adds", "or", "replaces", "the", "attribute", "with", "the", "given", "value", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/request.go#L106-L108
146,749
emicklei/go-restful
filter.go
ProcessFilter
func (f *FilterChain) ProcessFilter(request *Request, response *Response) { if f.Index < len(f.Filters) { f.Index++ f.Filters[f.Index-1](request, response, f) } else { f.Target(request, response) } }
go
func (f *FilterChain) ProcessFilter(request *Request, response *Response) { if f.Index < len(f.Filters) { f.Index++ f.Filters[f.Index-1](request, response, f) } else { f.Target(request, response) } }
[ "func", "(", "f", "*", "FilterChain", ")", "ProcessFilter", "(", "request", "*", "Request", ",", "response", "*", "Response", ")", "{", "if", "f", ".", "Index", "<", "len", "(", "f", ".", "Filters", ")", "{", "f", ".", "Index", "++", "\n", "f", ".", "Filters", "[", "f", ".", "Index", "-", "1", "]", "(", "request", ",", "response", ",", "f", ")", "\n", "}", "else", "{", "f", ".", "Target", "(", "request", ",", "response", ")", "\n", "}", "\n", "}" ]
// ProcessFilter passes the request,response pair through the next of Filters. // Each filter can decide to proceed to the next Filter or handle the Response itself.
[ "ProcessFilter", "passes", "the", "request", "response", "pair", "through", "the", "next", "of", "Filters", ".", "Each", "filter", "can", "decide", "to", "proceed", "to", "the", "next", "Filter", "or", "handle", "the", "Response", "itself", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/filter.go#L16-L23
146,750
emicklei/go-restful
route.go
wrapRequestResponse
func (r *Route) wrapRequestResponse(httpWriter http.ResponseWriter, httpRequest *http.Request, pathParams map[string]string) (*Request, *Response) { wrappedRequest := NewRequest(httpRequest) wrappedRequest.pathParameters = pathParams wrappedRequest.selectedRoutePath = r.Path wrappedResponse := NewResponse(httpWriter) wrappedResponse.requestAccept = httpRequest.Header.Get(HEADER_Accept) wrappedResponse.routeProduces = r.Produces return wrappedRequest, wrappedResponse }
go
func (r *Route) wrapRequestResponse(httpWriter http.ResponseWriter, httpRequest *http.Request, pathParams map[string]string) (*Request, *Response) { wrappedRequest := NewRequest(httpRequest) wrappedRequest.pathParameters = pathParams wrappedRequest.selectedRoutePath = r.Path wrappedResponse := NewResponse(httpWriter) wrappedResponse.requestAccept = httpRequest.Header.Get(HEADER_Accept) wrappedResponse.routeProduces = r.Produces return wrappedRequest, wrappedResponse }
[ "func", "(", "r", "*", "Route", ")", "wrapRequestResponse", "(", "httpWriter", "http", ".", "ResponseWriter", ",", "httpRequest", "*", "http", ".", "Request", ",", "pathParams", "map", "[", "string", "]", "string", ")", "(", "*", "Request", ",", "*", "Response", ")", "{", "wrappedRequest", ":=", "NewRequest", "(", "httpRequest", ")", "\n", "wrappedRequest", ".", "pathParameters", "=", "pathParams", "\n", "wrappedRequest", ".", "selectedRoutePath", "=", "r", ".", "Path", "\n", "wrappedResponse", ":=", "NewResponse", "(", "httpWriter", ")", "\n", "wrappedResponse", ".", "requestAccept", "=", "httpRequest", ".", "Header", ".", "Get", "(", "HEADER_Accept", ")", "\n", "wrappedResponse", ".", "routeProduces", "=", "r", ".", "Produces", "\n", "return", "wrappedRequest", ",", "wrappedResponse", "\n", "}" ]
// Create Request and Response from their http versions
[ "Create", "Request", "and", "Response", "from", "their", "http", "versions" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route.go#L60-L68
146,751
emicklei/go-restful
route.go
dispatchWithFilters
func (r *Route) dispatchWithFilters(wrappedRequest *Request, wrappedResponse *Response) { if len(r.Filters) > 0 { chain := FilterChain{Filters: r.Filters, Target: r.Function} chain.ProcessFilter(wrappedRequest, wrappedResponse) } else { // unfiltered r.Function(wrappedRequest, wrappedResponse) } }
go
func (r *Route) dispatchWithFilters(wrappedRequest *Request, wrappedResponse *Response) { if len(r.Filters) > 0 { chain := FilterChain{Filters: r.Filters, Target: r.Function} chain.ProcessFilter(wrappedRequest, wrappedResponse) } else { // unfiltered r.Function(wrappedRequest, wrappedResponse) } }
[ "func", "(", "r", "*", "Route", ")", "dispatchWithFilters", "(", "wrappedRequest", "*", "Request", ",", "wrappedResponse", "*", "Response", ")", "{", "if", "len", "(", "r", ".", "Filters", ")", ">", "0", "{", "chain", ":=", "FilterChain", "{", "Filters", ":", "r", ".", "Filters", ",", "Target", ":", "r", ".", "Function", "}", "\n", "chain", ".", "ProcessFilter", "(", "wrappedRequest", ",", "wrappedResponse", ")", "\n", "}", "else", "{", "// unfiltered", "r", ".", "Function", "(", "wrappedRequest", ",", "wrappedResponse", ")", "\n", "}", "\n", "}" ]
// dispatchWithFilters call the function after passing through its own filters
[ "dispatchWithFilters", "call", "the", "function", "after", "passing", "through", "its", "own", "filters" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route.go#L71-L79
146,752
emicklei/go-restful
route.go
matchesAccept
func (r Route) matchesAccept(mimeTypesWithQuality string) bool { remaining := mimeTypesWithQuality for { var mimeType string if end := strings.Index(remaining, ","); end == -1 { mimeType, remaining = remaining, "" } else { mimeType, remaining = remaining[:end], remaining[end+1:] } if quality := strings.Index(mimeType, ";"); quality != -1 { mimeType = mimeType[:quality] } mimeType = strings.TrimFunc(mimeType, stringTrimSpaceCutset) if mimeType == "*/*" { return true } for _, producibleType := range r.Produces { if producibleType == "*/*" || producibleType == mimeType { return true } } if len(remaining) == 0 { return false } } }
go
func (r Route) matchesAccept(mimeTypesWithQuality string) bool { remaining := mimeTypesWithQuality for { var mimeType string if end := strings.Index(remaining, ","); end == -1 { mimeType, remaining = remaining, "" } else { mimeType, remaining = remaining[:end], remaining[end+1:] } if quality := strings.Index(mimeType, ";"); quality != -1 { mimeType = mimeType[:quality] } mimeType = strings.TrimFunc(mimeType, stringTrimSpaceCutset) if mimeType == "*/*" { return true } for _, producibleType := range r.Produces { if producibleType == "*/*" || producibleType == mimeType { return true } } if len(remaining) == 0 { return false } } }
[ "func", "(", "r", "Route", ")", "matchesAccept", "(", "mimeTypesWithQuality", "string", ")", "bool", "{", "remaining", ":=", "mimeTypesWithQuality", "\n", "for", "{", "var", "mimeType", "string", "\n", "if", "end", ":=", "strings", ".", "Index", "(", "remaining", ",", "\"", "\"", ")", ";", "end", "==", "-", "1", "{", "mimeType", ",", "remaining", "=", "remaining", ",", "\"", "\"", "\n", "}", "else", "{", "mimeType", ",", "remaining", "=", "remaining", "[", ":", "end", "]", ",", "remaining", "[", "end", "+", "1", ":", "]", "\n", "}", "\n", "if", "quality", ":=", "strings", ".", "Index", "(", "mimeType", ",", "\"", "\"", ")", ";", "quality", "!=", "-", "1", "{", "mimeType", "=", "mimeType", "[", ":", "quality", "]", "\n", "}", "\n", "mimeType", "=", "strings", ".", "TrimFunc", "(", "mimeType", ",", "stringTrimSpaceCutset", ")", "\n", "if", "mimeType", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "producibleType", ":=", "range", "r", ".", "Produces", "{", "if", "producibleType", "==", "\"", "\"", "||", "producibleType", "==", "mimeType", "{", "return", "true", "\n", "}", "\n", "}", "\n", "if", "len", "(", "remaining", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}" ]
// Return whether the mimeType matches to what this Route can produce.
[ "Return", "whether", "the", "mimeType", "matches", "to", "what", "this", "Route", "can", "produce", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route.go#L86-L111
146,753
emicklei/go-restful
route.go
tokenizePath
func tokenizePath(path string) []string { if "/" == path { return nil } return strings.Split(strings.Trim(path, "/"), "/") }
go
func tokenizePath(path string) []string { if "/" == path { return nil } return strings.Split(strings.Trim(path, "/"), "/") }
[ "func", "tokenizePath", "(", "path", "string", ")", "[", "]", "string", "{", "if", "\"", "\"", "==", "path", "{", "return", "nil", "\n", "}", "\n", "return", "strings", ".", "Split", "(", "strings", ".", "Trim", "(", "path", ",", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "}" ]
// Tokenize an URL path using the slash separator ; the result does not have empty tokens
[ "Tokenize", "an", "URL", "path", "using", "the", "slash", "separator", ";", "the", "result", "does", "not", "have", "empty", "tokens" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/route.go#L155-L160
146,754
emicklei/go-restful
examples/msgpack/msgpack_entity.go
Read
func (e entityMsgPackAccess) Read(req *restful.Request, v interface{}) error { return msgpack.NewDecoder(req.Request.Body).Decode(v) }
go
func (e entityMsgPackAccess) Read(req *restful.Request, v interface{}) error { return msgpack.NewDecoder(req.Request.Body).Decode(v) }
[ "func", "(", "e", "entityMsgPackAccess", ")", "Read", "(", "req", "*", "restful", ".", "Request", ",", "v", "interface", "{", "}", ")", "error", "{", "return", "msgpack", ".", "NewDecoder", "(", "req", ".", "Request", ".", "Body", ")", ".", "Decode", "(", "v", ")", "\n", "}" ]
// Read unmarshalls the value from byte slice and using msgpack to unmarshal
[ "Read", "unmarshalls", "the", "value", "from", "byte", "slice", "and", "using", "msgpack", "to", "unmarshal" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/examples/msgpack/msgpack_entity.go#L21-L23
146,755
emicklei/go-restful
examples/msgpack/msgpack_entity.go
Write
func (e entityMsgPackAccess) Write(resp *restful.Response, status int, v interface{}) error { if v == nil { resp.WriteHeader(status) // do not write a nil representation return nil } resp.WriteHeader(status) return msgpack.NewEncoder(resp).Encode(v) }
go
func (e entityMsgPackAccess) Write(resp *restful.Response, status int, v interface{}) error { if v == nil { resp.WriteHeader(status) // do not write a nil representation return nil } resp.WriteHeader(status) return msgpack.NewEncoder(resp).Encode(v) }
[ "func", "(", "e", "entityMsgPackAccess", ")", "Write", "(", "resp", "*", "restful", ".", "Response", ",", "status", "int", ",", "v", "interface", "{", "}", ")", "error", "{", "if", "v", "==", "nil", "{", "resp", ".", "WriteHeader", "(", "status", ")", "\n", "// do not write a nil representation", "return", "nil", "\n", "}", "\n", "resp", ".", "WriteHeader", "(", "status", ")", "\n", "return", "msgpack", ".", "NewEncoder", "(", "resp", ")", ".", "Encode", "(", "v", ")", "\n", "}" ]
// Write marshals the value to byte slice and set the Content-Type Header.
[ "Write", "marshals", "the", "value", "to", "byte", "slice", "and", "set", "the", "Content", "-", "Type", "Header", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/examples/msgpack/msgpack_entity.go#L26-L34
146,756
emicklei/go-restful
jsr311.go
ExtractParameters
func (r RouterJSR311) ExtractParameters(route *Route, webService *WebService, urlPath string) map[string]string { webServiceExpr := webService.pathExpr webServiceMatches := webServiceExpr.Matcher.FindStringSubmatch(urlPath) pathParameters := r.extractParams(webServiceExpr, webServiceMatches) routeExpr := route.pathExpr routeMatches := routeExpr.Matcher.FindStringSubmatch(webServiceMatches[len(webServiceMatches)-1]) routeParams := r.extractParams(routeExpr, routeMatches) for key, value := range routeParams { pathParameters[key] = value } return pathParameters }
go
func (r RouterJSR311) ExtractParameters(route *Route, webService *WebService, urlPath string) map[string]string { webServiceExpr := webService.pathExpr webServiceMatches := webServiceExpr.Matcher.FindStringSubmatch(urlPath) pathParameters := r.extractParams(webServiceExpr, webServiceMatches) routeExpr := route.pathExpr routeMatches := routeExpr.Matcher.FindStringSubmatch(webServiceMatches[len(webServiceMatches)-1]) routeParams := r.extractParams(routeExpr, routeMatches) for key, value := range routeParams { pathParameters[key] = value } return pathParameters }
[ "func", "(", "r", "RouterJSR311", ")", "ExtractParameters", "(", "route", "*", "Route", ",", "webService", "*", "WebService", ",", "urlPath", "string", ")", "map", "[", "string", "]", "string", "{", "webServiceExpr", ":=", "webService", ".", "pathExpr", "\n", "webServiceMatches", ":=", "webServiceExpr", ".", "Matcher", ".", "FindStringSubmatch", "(", "urlPath", ")", "\n", "pathParameters", ":=", "r", ".", "extractParams", "(", "webServiceExpr", ",", "webServiceMatches", ")", "\n", "routeExpr", ":=", "route", ".", "pathExpr", "\n", "routeMatches", ":=", "routeExpr", ".", "Matcher", ".", "FindStringSubmatch", "(", "webServiceMatches", "[", "len", "(", "webServiceMatches", ")", "-", "1", "]", ")", "\n", "routeParams", ":=", "r", ".", "extractParams", "(", "routeExpr", ",", "routeMatches", ")", "\n", "for", "key", ",", "value", ":=", "range", "routeParams", "{", "pathParameters", "[", "key", "]", "=", "value", "\n", "}", "\n", "return", "pathParameters", "\n", "}" ]
// ExtractParameters is used to obtain the path parameters from the route using the same matching // engine as the JSR 311 router.
[ "ExtractParameters", "is", "used", "to", "obtain", "the", "path", "parameters", "from", "the", "route", "using", "the", "same", "matching", "engine", "as", "the", "JSR", "311", "router", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/jsr311.go#L44-L55
146,757
emicklei/go-restful
container.go
Add
func (c *Container) Add(service *WebService) *Container { c.webServicesLock.Lock() defer c.webServicesLock.Unlock() // if rootPath was not set then lazy initialize it if len(service.rootPath) == 0 { service.Path("/") } // cannot have duplicate root paths for _, each := range c.webServices { if each.RootPath() == service.RootPath() { log.Printf("WebService with duplicate root path detected:['%v']", each) os.Exit(1) } } // If not registered on root then add specific mapping if !c.isRegisteredOnRoot { c.isRegisteredOnRoot = c.addHandler(service, c.ServeMux) } c.webServices = append(c.webServices, service) return c }
go
func (c *Container) Add(service *WebService) *Container { c.webServicesLock.Lock() defer c.webServicesLock.Unlock() // if rootPath was not set then lazy initialize it if len(service.rootPath) == 0 { service.Path("/") } // cannot have duplicate root paths for _, each := range c.webServices { if each.RootPath() == service.RootPath() { log.Printf("WebService with duplicate root path detected:['%v']", each) os.Exit(1) } } // If not registered on root then add specific mapping if !c.isRegisteredOnRoot { c.isRegisteredOnRoot = c.addHandler(service, c.ServeMux) } c.webServices = append(c.webServices, service) return c }
[ "func", "(", "c", "*", "Container", ")", "Add", "(", "service", "*", "WebService", ")", "*", "Container", "{", "c", ".", "webServicesLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "webServicesLock", ".", "Unlock", "(", ")", "\n\n", "// if rootPath was not set then lazy initialize it", "if", "len", "(", "service", ".", "rootPath", ")", "==", "0", "{", "service", ".", "Path", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// cannot have duplicate root paths", "for", "_", ",", "each", ":=", "range", "c", ".", "webServices", "{", "if", "each", ".", "RootPath", "(", ")", "==", "service", ".", "RootPath", "(", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "each", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", "\n\n", "// If not registered on root then add specific mapping", "if", "!", "c", ".", "isRegisteredOnRoot", "{", "c", ".", "isRegisteredOnRoot", "=", "c", ".", "addHandler", "(", "service", ",", "c", ".", "ServeMux", ")", "\n", "}", "\n", "c", ".", "webServices", "=", "append", "(", "c", ".", "webServices", ",", "service", ")", "\n", "return", "c", "\n", "}" ]
// Add a WebService to the Container. It will detect duplicate root paths and exit in that case.
[ "Add", "a", "WebService", "to", "the", "Container", ".", "It", "will", "detect", "duplicate", "root", "paths", "and", "exit", "in", "that", "case", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/container.go#L88-L111
146,758
emicklei/go-restful
container.go
logStackOnRecover
func logStackOnRecover(panicReason interface{}, httpWriter http.ResponseWriter) { var buffer bytes.Buffer buffer.WriteString(fmt.Sprintf("recover from panic situation: - %v\r\n", panicReason)) for i := 2; ; i += 1 { _, file, line, ok := runtime.Caller(i) if !ok { break } buffer.WriteString(fmt.Sprintf(" %s:%d\r\n", file, line)) } log.Print(buffer.String()) httpWriter.WriteHeader(http.StatusInternalServerError) httpWriter.Write(buffer.Bytes()) }
go
func logStackOnRecover(panicReason interface{}, httpWriter http.ResponseWriter) { var buffer bytes.Buffer buffer.WriteString(fmt.Sprintf("recover from panic situation: - %v\r\n", panicReason)) for i := 2; ; i += 1 { _, file, line, ok := runtime.Caller(i) if !ok { break } buffer.WriteString(fmt.Sprintf(" %s:%d\r\n", file, line)) } log.Print(buffer.String()) httpWriter.WriteHeader(http.StatusInternalServerError) httpWriter.Write(buffer.Bytes()) }
[ "func", "logStackOnRecover", "(", "panicReason", "interface", "{", "}", ",", "httpWriter", "http", ".", "ResponseWriter", ")", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\r", "\\n", "\"", ",", "panicReason", ")", ")", "\n", "for", "i", ":=", "2", ";", ";", "i", "+=", "1", "{", "_", ",", "file", ",", "line", ",", "ok", ":=", "runtime", ".", "Caller", "(", "i", ")", "\n", "if", "!", "ok", "{", "break", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\r", "\\n", "\"", ",", "file", ",", "line", ")", ")", "\n", "}", "\n", "log", ".", "Print", "(", "buffer", ".", "String", "(", ")", ")", "\n", "httpWriter", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "httpWriter", ".", "Write", "(", "buffer", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// logStackOnRecover is the default RecoverHandleFunction and is called // when DoNotRecover is false and the recoverHandleFunc is not set for the container. // Default implementation logs the stacktrace and writes the stacktrace on the response. // This may be a security issue as it exposes sourcecode information.
[ "logStackOnRecover", "is", "the", "default", "RecoverHandleFunction", "and", "is", "called", "when", "DoNotRecover", "is", "false", "and", "the", "recoverHandleFunc", "is", "not", "set", "for", "the", "container", ".", "Default", "implementation", "logs", "the", "stacktrace", "and", "writes", "the", "stacktrace", "on", "the", "response", ".", "This", "may", "be", "a", "security", "issue", "as", "it", "exposes", "sourcecode", "information", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/container.go#L169-L182
146,759
emicklei/go-restful
container.go
HandleWithFilter
func (c *Container) HandleWithFilter(pattern string, handler http.Handler) { f := func(httpResponse http.ResponseWriter, httpRequest *http.Request) { if len(c.containerFilters) == 0 { handler.ServeHTTP(httpResponse, httpRequest) return } chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) { handler.ServeHTTP(httpResponse, httpRequest) }} chain.ProcessFilter(NewRequest(httpRequest), NewResponse(httpResponse)) } c.Handle(pattern, http.HandlerFunc(f)) }
go
func (c *Container) HandleWithFilter(pattern string, handler http.Handler) { f := func(httpResponse http.ResponseWriter, httpRequest *http.Request) { if len(c.containerFilters) == 0 { handler.ServeHTTP(httpResponse, httpRequest) return } chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) { handler.ServeHTTP(httpResponse, httpRequest) }} chain.ProcessFilter(NewRequest(httpRequest), NewResponse(httpResponse)) } c.Handle(pattern, http.HandlerFunc(f)) }
[ "func", "(", "c", "*", "Container", ")", "HandleWithFilter", "(", "pattern", "string", ",", "handler", "http", ".", "Handler", ")", "{", "f", ":=", "func", "(", "httpResponse", "http", ".", "ResponseWriter", ",", "httpRequest", "*", "http", ".", "Request", ")", "{", "if", "len", "(", "c", ".", "containerFilters", ")", "==", "0", "{", "handler", ".", "ServeHTTP", "(", "httpResponse", ",", "httpRequest", ")", "\n", "return", "\n", "}", "\n\n", "chain", ":=", "FilterChain", "{", "Filters", ":", "c", ".", "containerFilters", ",", "Target", ":", "func", "(", "req", "*", "Request", ",", "resp", "*", "Response", ")", "{", "handler", ".", "ServeHTTP", "(", "httpResponse", ",", "httpRequest", ")", "\n", "}", "}", "\n", "chain", ".", "ProcessFilter", "(", "NewRequest", "(", "httpRequest", ")", ",", "NewResponse", "(", "httpResponse", ")", ")", "\n", "}", "\n\n", "c", ".", "Handle", "(", "pattern", ",", "http", ".", "HandlerFunc", "(", "f", ")", ")", "\n", "}" ]
// HandleWithFilter registers the handler for the given pattern. // Container's filter chain is applied for handler. // If a handler already exists for pattern, HandleWithFilter panics.
[ "HandleWithFilter", "registers", "the", "handler", "for", "the", "given", "pattern", ".", "Container", "s", "filter", "chain", "is", "applied", "for", "handler", ".", "If", "a", "handler", "already", "exists", "for", "pattern", "HandleWithFilter", "panics", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/container.go#L314-L328
146,760
emicklei/go-restful
container.go
Filter
func (c *Container) Filter(filter FilterFunction) { c.containerFilters = append(c.containerFilters, filter) }
go
func (c *Container) Filter(filter FilterFunction) { c.containerFilters = append(c.containerFilters, filter) }
[ "func", "(", "c", "*", "Container", ")", "Filter", "(", "filter", "FilterFunction", ")", "{", "c", ".", "containerFilters", "=", "append", "(", "c", ".", "containerFilters", ",", "filter", ")", "\n", "}" ]
// Filter appends a container FilterFunction. These are called before dispatching // a http.Request to a WebService from the container
[ "Filter", "appends", "a", "container", "FilterFunction", ".", "These", "are", "called", "before", "dispatching", "a", "http", ".", "Request", "to", "a", "WebService", "from", "the", "container" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/container.go#L332-L334
146,761
emicklei/go-restful
container.go
RegisteredWebServices
func (c *Container) RegisteredWebServices() []*WebService { c.webServicesLock.RLock() defer c.webServicesLock.RUnlock() result := make([]*WebService, len(c.webServices)) for ix := range c.webServices { result[ix] = c.webServices[ix] } return result }
go
func (c *Container) RegisteredWebServices() []*WebService { c.webServicesLock.RLock() defer c.webServicesLock.RUnlock() result := make([]*WebService, len(c.webServices)) for ix := range c.webServices { result[ix] = c.webServices[ix] } return result }
[ "func", "(", "c", "*", "Container", ")", "RegisteredWebServices", "(", ")", "[", "]", "*", "WebService", "{", "c", ".", "webServicesLock", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "webServicesLock", ".", "RUnlock", "(", ")", "\n", "result", ":=", "make", "(", "[", "]", "*", "WebService", ",", "len", "(", "c", ".", "webServices", ")", ")", "\n", "for", "ix", ":=", "range", "c", ".", "webServices", "{", "result", "[", "ix", "]", "=", "c", ".", "webServices", "[", "ix", "]", "\n", "}", "\n", "return", "result", "\n", "}" ]
// RegisteredWebServices returns the collections of added WebServices
[ "RegisteredWebServices", "returns", "the", "collections", "of", "added", "WebServices" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/container.go#L337-L345
146,762
emicklei/go-restful
container.go
computeAllowedMethods
func (c *Container) computeAllowedMethods(req *Request) []string { // Go through all RegisteredWebServices() and all its Routes to collect the options methods := []string{} requestPath := req.Request.URL.Path for _, ws := range c.RegisteredWebServices() { matches := ws.pathExpr.Matcher.FindStringSubmatch(requestPath) if matches != nil { finalMatch := matches[len(matches)-1] for _, rt := range ws.Routes() { matches := rt.pathExpr.Matcher.FindStringSubmatch(finalMatch) if matches != nil { lastMatch := matches[len(matches)-1] if lastMatch == "" || lastMatch == "/" { // do not include if value is neither empty nor ‘/’. methods = append(methods, rt.Method) } } } } } // methods = append(methods, "OPTIONS") not sure about this return methods }
go
func (c *Container) computeAllowedMethods(req *Request) []string { // Go through all RegisteredWebServices() and all its Routes to collect the options methods := []string{} requestPath := req.Request.URL.Path for _, ws := range c.RegisteredWebServices() { matches := ws.pathExpr.Matcher.FindStringSubmatch(requestPath) if matches != nil { finalMatch := matches[len(matches)-1] for _, rt := range ws.Routes() { matches := rt.pathExpr.Matcher.FindStringSubmatch(finalMatch) if matches != nil { lastMatch := matches[len(matches)-1] if lastMatch == "" || lastMatch == "/" { // do not include if value is neither empty nor ‘/’. methods = append(methods, rt.Method) } } } } } // methods = append(methods, "OPTIONS") not sure about this return methods }
[ "func", "(", "c", "*", "Container", ")", "computeAllowedMethods", "(", "req", "*", "Request", ")", "[", "]", "string", "{", "// Go through all RegisteredWebServices() and all its Routes to collect the options", "methods", ":=", "[", "]", "string", "{", "}", "\n", "requestPath", ":=", "req", ".", "Request", ".", "URL", ".", "Path", "\n", "for", "_", ",", "ws", ":=", "range", "c", ".", "RegisteredWebServices", "(", ")", "{", "matches", ":=", "ws", ".", "pathExpr", ".", "Matcher", ".", "FindStringSubmatch", "(", "requestPath", ")", "\n", "if", "matches", "!=", "nil", "{", "finalMatch", ":=", "matches", "[", "len", "(", "matches", ")", "-", "1", "]", "\n", "for", "_", ",", "rt", ":=", "range", "ws", ".", "Routes", "(", ")", "{", "matches", ":=", "rt", ".", "pathExpr", ".", "Matcher", ".", "FindStringSubmatch", "(", "finalMatch", ")", "\n", "if", "matches", "!=", "nil", "{", "lastMatch", ":=", "matches", "[", "len", "(", "matches", ")", "-", "1", "]", "\n", "if", "lastMatch", "==", "\"", "\"", "||", "lastMatch", "==", "\"", "\"", "{", "// do not include if value is neither empty nor ‘/’.", "methods", "=", "append", "(", "methods", ",", "rt", ".", "Method", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "// methods = append(methods, \"OPTIONS\") not sure about this", "return", "methods", "\n", "}" ]
// computeAllowedMethods returns a list of HTTP methods that are valid for a Request
[ "computeAllowedMethods", "returns", "a", "list", "of", "HTTP", "methods", "that", "are", "valid", "for", "a", "Request" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/container.go#L348-L369
146,763
emicklei/go-restful
compress.go
Write
func (c *CompressingResponseWriter) Write(bytes []byte) (int, error) { if c.isCompressorClosed() { return -1, errors.New("Compressing error: tried to write data using closed compressor") } return c.compressor.Write(bytes) }
go
func (c *CompressingResponseWriter) Write(bytes []byte) (int, error) { if c.isCompressorClosed() { return -1, errors.New("Compressing error: tried to write data using closed compressor") } return c.compressor.Write(bytes) }
[ "func", "(", "c", "*", "CompressingResponseWriter", ")", "Write", "(", "bytes", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "c", ".", "isCompressorClosed", "(", ")", "{", "return", "-", "1", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "compressor", ".", "Write", "(", "bytes", ")", "\n", "}" ]
// Write is part of http.ResponseWriter interface // It is passed through the compressor
[ "Write", "is", "part", "of", "http", ".", "ResponseWriter", "interface", "It", "is", "passed", "through", "the", "compressor" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/compress.go#L40-L45
146,764
emicklei/go-restful
compress.go
wantsCompressedResponse
func wantsCompressedResponse(httpRequest *http.Request) (bool, string) { header := httpRequest.Header.Get(HEADER_AcceptEncoding) gi := strings.Index(header, ENCODING_GZIP) zi := strings.Index(header, ENCODING_DEFLATE) // use in order of appearance if gi == -1 { return zi != -1, ENCODING_DEFLATE } else if zi == -1 { return gi != -1, ENCODING_GZIP } else { if gi < zi { return true, ENCODING_GZIP } return true, ENCODING_DEFLATE } }
go
func wantsCompressedResponse(httpRequest *http.Request) (bool, string) { header := httpRequest.Header.Get(HEADER_AcceptEncoding) gi := strings.Index(header, ENCODING_GZIP) zi := strings.Index(header, ENCODING_DEFLATE) // use in order of appearance if gi == -1 { return zi != -1, ENCODING_DEFLATE } else if zi == -1 { return gi != -1, ENCODING_GZIP } else { if gi < zi { return true, ENCODING_GZIP } return true, ENCODING_DEFLATE } }
[ "func", "wantsCompressedResponse", "(", "httpRequest", "*", "http", ".", "Request", ")", "(", "bool", ",", "string", ")", "{", "header", ":=", "httpRequest", ".", "Header", ".", "Get", "(", "HEADER_AcceptEncoding", ")", "\n", "gi", ":=", "strings", ".", "Index", "(", "header", ",", "ENCODING_GZIP", ")", "\n", "zi", ":=", "strings", ".", "Index", "(", "header", ",", "ENCODING_DEFLATE", ")", "\n", "// use in order of appearance", "if", "gi", "==", "-", "1", "{", "return", "zi", "!=", "-", "1", ",", "ENCODING_DEFLATE", "\n", "}", "else", "if", "zi", "==", "-", "1", "{", "return", "gi", "!=", "-", "1", ",", "ENCODING_GZIP", "\n", "}", "else", "{", "if", "gi", "<", "zi", "{", "return", "true", ",", "ENCODING_GZIP", "\n", "}", "\n", "return", "true", ",", "ENCODING_DEFLATE", "\n", "}", "\n", "}" ]
// WantsCompressedResponse reads the Accept-Encoding header to see if and which encoding is requested.
[ "WantsCompressedResponse", "reads", "the", "Accept", "-", "Encoding", "header", "to", "see", "if", "and", "which", "encoding", "is", "requested", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/compress.go#L86-L101
146,765
emicklei/go-restful
path_processor.go
ExtractParameters
func (d defaultPathProcessor) ExtractParameters(r *Route, _ *WebService, urlPath string) map[string]string { urlParts := tokenizePath(urlPath) pathParameters := map[string]string{} for i, key := range r.pathParts { var value string if i >= len(urlParts) { value = "" } else { value = urlParts[i] } if strings.HasPrefix(key, "{") { // path-parameter if colon := strings.Index(key, ":"); colon != -1 { // extract by regex regPart := key[colon+1 : len(key)-1] keyPart := key[1:colon] if regPart == "*" { pathParameters[keyPart] = untokenizePath(i, urlParts) break } else { pathParameters[keyPart] = value } } else { // without enclosing {} pathParameters[key[1:len(key)-1]] = value } } } return pathParameters }
go
func (d defaultPathProcessor) ExtractParameters(r *Route, _ *WebService, urlPath string) map[string]string { urlParts := tokenizePath(urlPath) pathParameters := map[string]string{} for i, key := range r.pathParts { var value string if i >= len(urlParts) { value = "" } else { value = urlParts[i] } if strings.HasPrefix(key, "{") { // path-parameter if colon := strings.Index(key, ":"); colon != -1 { // extract by regex regPart := key[colon+1 : len(key)-1] keyPart := key[1:colon] if regPart == "*" { pathParameters[keyPart] = untokenizePath(i, urlParts) break } else { pathParameters[keyPart] = value } } else { // without enclosing {} pathParameters[key[1:len(key)-1]] = value } } } return pathParameters }
[ "func", "(", "d", "defaultPathProcessor", ")", "ExtractParameters", "(", "r", "*", "Route", ",", "_", "*", "WebService", ",", "urlPath", "string", ")", "map", "[", "string", "]", "string", "{", "urlParts", ":=", "tokenizePath", "(", "urlPath", ")", "\n", "pathParameters", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "i", ",", "key", ":=", "range", "r", ".", "pathParts", "{", "var", "value", "string", "\n", "if", "i", ">=", "len", "(", "urlParts", ")", "{", "value", "=", "\"", "\"", "\n", "}", "else", "{", "value", "=", "urlParts", "[", "i", "]", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "key", ",", "\"", "\"", ")", "{", "// path-parameter", "if", "colon", ":=", "strings", ".", "Index", "(", "key", ",", "\"", "\"", ")", ";", "colon", "!=", "-", "1", "{", "// extract by regex", "regPart", ":=", "key", "[", "colon", "+", "1", ":", "len", "(", "key", ")", "-", "1", "]", "\n", "keyPart", ":=", "key", "[", "1", ":", "colon", "]", "\n", "if", "regPart", "==", "\"", "\"", "{", "pathParameters", "[", "keyPart", "]", "=", "untokenizePath", "(", "i", ",", "urlParts", ")", "\n", "break", "\n", "}", "else", "{", "pathParameters", "[", "keyPart", "]", "=", "value", "\n", "}", "\n", "}", "else", "{", "// without enclosing {}", "pathParameters", "[", "key", "[", "1", ":", "len", "(", "key", ")", "-", "1", "]", "]", "=", "value", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "pathParameters", "\n", "}" ]
// Extract the parameters from the request url path
[ "Extract", "the", "parameters", "from", "the", "request", "url", "path" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/path_processor.go#L22-L50
146,766
emicklei/go-restful
path_processor.go
untokenizePath
func untokenizePath(offset int, parts []string) string { var buffer bytes.Buffer for p := offset; p < len(parts); p++ { buffer.WriteString(parts[p]) // do not end if p < len(parts)-1 { buffer.WriteString("/") } } return buffer.String() }
go
func untokenizePath(offset int, parts []string) string { var buffer bytes.Buffer for p := offset; p < len(parts); p++ { buffer.WriteString(parts[p]) // do not end if p < len(parts)-1 { buffer.WriteString("/") } } return buffer.String() }
[ "func", "untokenizePath", "(", "offset", "int", ",", "parts", "[", "]", "string", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "for", "p", ":=", "offset", ";", "p", "<", "len", "(", "parts", ")", ";", "p", "++", "{", "buffer", ".", "WriteString", "(", "parts", "[", "p", "]", ")", "\n", "// do not end", "if", "p", "<", "len", "(", "parts", ")", "-", "1", "{", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "buffer", ".", "String", "(", ")", "\n", "}" ]
// Untokenize back into an URL path using the slash separator
[ "Untokenize", "back", "into", "an", "URL", "path", "using", "the", "slash", "separator" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/path_processor.go#L53-L63
146,767
emicklei/go-restful
web_service.go
compilePathExpression
func (w *WebService) compilePathExpression() { compiled, err := newPathExpression(w.rootPath) if err != nil { log.Printf("invalid path:%s because:%v", w.rootPath, err) os.Exit(1) } w.pathExpr = compiled }
go
func (w *WebService) compilePathExpression() { compiled, err := newPathExpression(w.rootPath) if err != nil { log.Printf("invalid path:%s because:%v", w.rootPath, err) os.Exit(1) } w.pathExpr = compiled }
[ "func", "(", "w", "*", "WebService", ")", "compilePathExpression", "(", ")", "{", "compiled", ",", "err", ":=", "newPathExpression", "(", "w", ".", "rootPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "w", ".", "rootPath", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "w", ".", "pathExpr", "=", "compiled", "\n", "}" ]
// compilePathExpression ensures that the path is compiled into a RegEx for those routers that need it.
[ "compilePathExpression", "ensures", "that", "the", "path", "is", "compiled", "into", "a", "RegEx", "for", "those", "routers", "that", "need", "it", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L60-L67
146,768
emicklei/go-restful
web_service.go
ApiVersion
func (w *WebService) ApiVersion(apiVersion string) *WebService { w.apiVersion = apiVersion return w }
go
func (w *WebService) ApiVersion(apiVersion string) *WebService { w.apiVersion = apiVersion return w }
[ "func", "(", "w", "*", "WebService", ")", "ApiVersion", "(", "apiVersion", "string", ")", "*", "WebService", "{", "w", ".", "apiVersion", "=", "apiVersion", "\n", "return", "w", "\n", "}" ]
// ApiVersion sets the API version for documentation purposes.
[ "ApiVersion", "sets", "the", "API", "version", "for", "documentation", "purposes", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L70-L73
146,769
emicklei/go-restful
web_service.go
Path
func (w *WebService) Path(root string) *WebService { w.rootPath = root if len(w.rootPath) == 0 { w.rootPath = "/" } w.compilePathExpression() return w }
go
func (w *WebService) Path(root string) *WebService { w.rootPath = root if len(w.rootPath) == 0 { w.rootPath = "/" } w.compilePathExpression() return w }
[ "func", "(", "w", "*", "WebService", ")", "Path", "(", "root", "string", ")", "*", "WebService", "{", "w", ".", "rootPath", "=", "root", "\n", "if", "len", "(", "w", ".", "rootPath", ")", "==", "0", "{", "w", ".", "rootPath", "=", "\"", "\"", "\n", "}", "\n", "w", ".", "compilePathExpression", "(", ")", "\n", "return", "w", "\n", "}" ]
// Path specifies the root URL template path of the WebService. // All Routes will be relative to this path.
[ "Path", "specifies", "the", "root", "URL", "template", "path", "of", "the", "WebService", ".", "All", "Routes", "will", "be", "relative", "to", "this", "path", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L80-L87
146,770
emicklei/go-restful
web_service.go
Param
func (w *WebService) Param(parameter *Parameter) *WebService { if w.pathParameters == nil { w.pathParameters = []*Parameter{} } w.pathParameters = append(w.pathParameters, parameter) return w }
go
func (w *WebService) Param(parameter *Parameter) *WebService { if w.pathParameters == nil { w.pathParameters = []*Parameter{} } w.pathParameters = append(w.pathParameters, parameter) return w }
[ "func", "(", "w", "*", "WebService", ")", "Param", "(", "parameter", "*", "Parameter", ")", "*", "WebService", "{", "if", "w", ".", "pathParameters", "==", "nil", "{", "w", ".", "pathParameters", "=", "[", "]", "*", "Parameter", "{", "}", "\n", "}", "\n", "w", ".", "pathParameters", "=", "append", "(", "w", ".", "pathParameters", ",", "parameter", ")", "\n", "return", "w", "\n", "}" ]
// Param adds a PathParameter to document parameters used in the root path.
[ "Param", "adds", "a", "PathParameter", "to", "document", "parameters", "used", "in", "the", "root", "path", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L90-L96
146,771
emicklei/go-restful
web_service.go
Route
func (w *WebService) Route(builder *RouteBuilder) *WebService { w.routesLock.Lock() defer w.routesLock.Unlock() builder.copyDefaults(w.produces, w.consumes) w.routes = append(w.routes, builder.Build()) return w }
go
func (w *WebService) Route(builder *RouteBuilder) *WebService { w.routesLock.Lock() defer w.routesLock.Unlock() builder.copyDefaults(w.produces, w.consumes) w.routes = append(w.routes, builder.Build()) return w }
[ "func", "(", "w", "*", "WebService", ")", "Route", "(", "builder", "*", "RouteBuilder", ")", "*", "WebService", "{", "w", ".", "routesLock", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "routesLock", ".", "Unlock", "(", ")", "\n", "builder", ".", "copyDefaults", "(", "w", ".", "produces", ",", "w", ".", "consumes", ")", "\n", "w", ".", "routes", "=", "append", "(", "w", ".", "routes", ",", "builder", ".", "Build", "(", ")", ")", "\n", "return", "w", "\n", "}" ]
// Route creates a new Route using the RouteBuilder and add to the ordered list of Routes.
[ "Route", "creates", "a", "new", "Route", "using", "the", "RouteBuilder", "and", "add", "to", "the", "ordered", "list", "of", "Routes", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L169-L175
146,772
emicklei/go-restful
web_service.go
RemoveRoute
func (w *WebService) RemoveRoute(path, method string) error { if !w.dynamicRoutes { return errors.New("dynamic routes are not enabled.") } w.routesLock.Lock() defer w.routesLock.Unlock() newRoutes := make([]Route, (len(w.routes) - 1)) current := 0 for ix := range w.routes { if w.routes[ix].Method == method && w.routes[ix].Path == path { continue } newRoutes[current] = w.routes[ix] current = current + 1 } w.routes = newRoutes return nil }
go
func (w *WebService) RemoveRoute(path, method string) error { if !w.dynamicRoutes { return errors.New("dynamic routes are not enabled.") } w.routesLock.Lock() defer w.routesLock.Unlock() newRoutes := make([]Route, (len(w.routes) - 1)) current := 0 for ix := range w.routes { if w.routes[ix].Method == method && w.routes[ix].Path == path { continue } newRoutes[current] = w.routes[ix] current = current + 1 } w.routes = newRoutes return nil }
[ "func", "(", "w", "*", "WebService", ")", "RemoveRoute", "(", "path", ",", "method", "string", ")", "error", "{", "if", "!", "w", ".", "dynamicRoutes", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "w", ".", "routesLock", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "routesLock", ".", "Unlock", "(", ")", "\n", "newRoutes", ":=", "make", "(", "[", "]", "Route", ",", "(", "len", "(", "w", ".", "routes", ")", "-", "1", ")", ")", "\n", "current", ":=", "0", "\n", "for", "ix", ":=", "range", "w", ".", "routes", "{", "if", "w", ".", "routes", "[", "ix", "]", ".", "Method", "==", "method", "&&", "w", ".", "routes", "[", "ix", "]", ".", "Path", "==", "path", "{", "continue", "\n", "}", "\n", "newRoutes", "[", "current", "]", "=", "w", ".", "routes", "[", "ix", "]", "\n", "current", "=", "current", "+", "1", "\n", "}", "\n", "w", ".", "routes", "=", "newRoutes", "\n", "return", "nil", "\n", "}" ]
// RemoveRoute removes the specified route, looks for something that matches 'path' and 'method'
[ "RemoveRoute", "removes", "the", "specified", "route", "looks", "for", "something", "that", "matches", "path", "and", "method" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L178-L195
146,773
emicklei/go-restful
web_service.go
Method
func (w *WebService) Method(httpMethod string) *RouteBuilder { return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method(httpMethod) }
go
func (w *WebService) Method(httpMethod string) *RouteBuilder { return new(RouteBuilder).typeNameHandler(w.typeNameHandleFunc).servicePath(w.rootPath).Method(httpMethod) }
[ "func", "(", "w", "*", "WebService", ")", "Method", "(", "httpMethod", "string", ")", "*", "RouteBuilder", "{", "return", "new", "(", "RouteBuilder", ")", ".", "typeNameHandler", "(", "w", ".", "typeNameHandleFunc", ")", ".", "servicePath", "(", "w", ".", "rootPath", ")", ".", "Method", "(", "httpMethod", ")", "\n", "}" ]
// Method creates a new RouteBuilder and initialize its http method
[ "Method", "creates", "a", "new", "RouteBuilder", "and", "initialize", "its", "http", "method" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L198-L200
146,774
emicklei/go-restful
web_service.go
Produces
func (w *WebService) Produces(contentTypes ...string) *WebService { w.produces = contentTypes return w }
go
func (w *WebService) Produces(contentTypes ...string) *WebService { w.produces = contentTypes return w }
[ "func", "(", "w", "*", "WebService", ")", "Produces", "(", "contentTypes", "...", "string", ")", "*", "WebService", "{", "w", ".", "produces", "=", "contentTypes", "\n", "return", "w", "\n", "}" ]
// Produces specifies that this WebService can produce one or more MIME types. // Http requests must have one of these values set for the Accept header.
[ "Produces", "specifies", "that", "this", "WebService", "can", "produce", "one", "or", "more", "MIME", "types", ".", "Http", "requests", "must", "have", "one", "of", "these", "values", "set", "for", "the", "Accept", "header", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L204-L207
146,775
emicklei/go-restful
web_service.go
Consumes
func (w *WebService) Consumes(accepts ...string) *WebService { w.consumes = accepts return w }
go
func (w *WebService) Consumes(accepts ...string) *WebService { w.consumes = accepts return w }
[ "func", "(", "w", "*", "WebService", ")", "Consumes", "(", "accepts", "...", "string", ")", "*", "WebService", "{", "w", ".", "consumes", "=", "accepts", "\n", "return", "w", "\n", "}" ]
// Consumes specifies that this WebService can consume one or more MIME types. // Http requests must have one of these values set for the Content-Type header.
[ "Consumes", "specifies", "that", "this", "WebService", "can", "consume", "one", "or", "more", "MIME", "types", ".", "Http", "requests", "must", "have", "one", "of", "these", "values", "set", "for", "the", "Content", "-", "Type", "header", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L211-L214
146,776
emicklei/go-restful
web_service.go
Routes
func (w *WebService) Routes() []Route { if !w.dynamicRoutes { return w.routes } // Make a copy of the array to prevent concurrency problems w.routesLock.RLock() defer w.routesLock.RUnlock() result := make([]Route, len(w.routes)) for ix := range w.routes { result[ix] = w.routes[ix] } return result }
go
func (w *WebService) Routes() []Route { if !w.dynamicRoutes { return w.routes } // Make a copy of the array to prevent concurrency problems w.routesLock.RLock() defer w.routesLock.RUnlock() result := make([]Route, len(w.routes)) for ix := range w.routes { result[ix] = w.routes[ix] } return result }
[ "func", "(", "w", "*", "WebService", ")", "Routes", "(", ")", "[", "]", "Route", "{", "if", "!", "w", ".", "dynamicRoutes", "{", "return", "w", ".", "routes", "\n", "}", "\n", "// Make a copy of the array to prevent concurrency problems", "w", ".", "routesLock", ".", "RLock", "(", ")", "\n", "defer", "w", ".", "routesLock", ".", "RUnlock", "(", ")", "\n", "result", ":=", "make", "(", "[", "]", "Route", ",", "len", "(", "w", ".", "routes", ")", ")", "\n", "for", "ix", ":=", "range", "w", ".", "routes", "{", "result", "[", "ix", "]", "=", "w", ".", "routes", "[", "ix", "]", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Routes returns the Routes associated with this WebService
[ "Routes", "returns", "the", "Routes", "associated", "with", "this", "WebService" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L217-L229
146,777
emicklei/go-restful
web_service.go
Filter
func (w *WebService) Filter(filter FilterFunction) *WebService { w.filters = append(w.filters, filter) return w }
go
func (w *WebService) Filter(filter FilterFunction) *WebService { w.filters = append(w.filters, filter) return w }
[ "func", "(", "w", "*", "WebService", ")", "Filter", "(", "filter", "FilterFunction", ")", "*", "WebService", "{", "w", ".", "filters", "=", "append", "(", "w", ".", "filters", ",", "filter", ")", "\n", "return", "w", "\n", "}" ]
// Filter adds a filter function to the chain of filters applicable to all its Routes
[ "Filter", "adds", "a", "filter", "function", "to", "the", "chain", "of", "filters", "applicable", "to", "all", "its", "Routes" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L242-L245
146,778
emicklei/go-restful
web_service.go
Doc
func (w *WebService) Doc(plainText string) *WebService { w.documentation = plainText return w }
go
func (w *WebService) Doc(plainText string) *WebService { w.documentation = plainText return w }
[ "func", "(", "w", "*", "WebService", ")", "Doc", "(", "plainText", "string", ")", "*", "WebService", "{", "w", ".", "documentation", "=", "plainText", "\n", "return", "w", "\n", "}" ]
// Doc is used to set the documentation of this service.
[ "Doc", "is", "used", "to", "set", "the", "documentation", "of", "this", "service", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/web_service.go#L248-L251
146,779
emicklei/go-restful
parameter.go
Required
func (p *Parameter) Required(required bool) *Parameter { p.data.Required = required return p }
go
func (p *Parameter) Required(required bool) *Parameter { p.data.Required = required return p }
[ "func", "(", "p", "*", "Parameter", ")", "Required", "(", "required", "bool", ")", "*", "Parameter", "{", "p", ".", "data", ".", "Required", "=", "required", "\n", "return", "p", "\n", "}" ]
// Required sets the required field and returns the receiver
[ "Required", "sets", "the", "required", "field", "and", "returns", "the", "receiver" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L98-L101
146,780
emicklei/go-restful
parameter.go
AllowMultiple
func (p *Parameter) AllowMultiple(multiple bool) *Parameter { p.data.AllowMultiple = multiple return p }
go
func (p *Parameter) AllowMultiple(multiple bool) *Parameter { p.data.AllowMultiple = multiple return p }
[ "func", "(", "p", "*", "Parameter", ")", "AllowMultiple", "(", "multiple", "bool", ")", "*", "Parameter", "{", "p", ".", "data", ".", "AllowMultiple", "=", "multiple", "\n", "return", "p", "\n", "}" ]
// AllowMultiple sets the allowMultiple field and returns the receiver
[ "AllowMultiple", "sets", "the", "allowMultiple", "field", "and", "returns", "the", "receiver" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L104-L107
146,781
emicklei/go-restful
parameter.go
AllowableValues
func (p *Parameter) AllowableValues(values map[string]string) *Parameter { p.data.AllowableValues = values return p }
go
func (p *Parameter) AllowableValues(values map[string]string) *Parameter { p.data.AllowableValues = values return p }
[ "func", "(", "p", "*", "Parameter", ")", "AllowableValues", "(", "values", "map", "[", "string", "]", "string", ")", "*", "Parameter", "{", "p", ".", "data", ".", "AllowableValues", "=", "values", "\n", "return", "p", "\n", "}" ]
// AllowableValues sets the allowableValues field and returns the receiver
[ "AllowableValues", "sets", "the", "allowableValues", "field", "and", "returns", "the", "receiver" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L110-L113
146,782
emicklei/go-restful
parameter.go
DataType
func (p *Parameter) DataType(typeName string) *Parameter { p.data.DataType = typeName return p }
go
func (p *Parameter) DataType(typeName string) *Parameter { p.data.DataType = typeName return p }
[ "func", "(", "p", "*", "Parameter", ")", "DataType", "(", "typeName", "string", ")", "*", "Parameter", "{", "p", ".", "data", ".", "DataType", "=", "typeName", "\n", "return", "p", "\n", "}" ]
// DataType sets the dataType field and returns the receiver
[ "DataType", "sets", "the", "dataType", "field", "and", "returns", "the", "receiver" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L116-L119
146,783
emicklei/go-restful
parameter.go
DataFormat
func (p *Parameter) DataFormat(formatName string) *Parameter { p.data.DataFormat = formatName return p }
go
func (p *Parameter) DataFormat(formatName string) *Parameter { p.data.DataFormat = formatName return p }
[ "func", "(", "p", "*", "Parameter", ")", "DataFormat", "(", "formatName", "string", ")", "*", "Parameter", "{", "p", ".", "data", ".", "DataFormat", "=", "formatName", "\n", "return", "p", "\n", "}" ]
// DataFormat sets the dataFormat field for Swagger UI
[ "DataFormat", "sets", "the", "dataFormat", "field", "for", "Swagger", "UI" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L122-L125
146,784
emicklei/go-restful
parameter.go
DefaultValue
func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter { p.data.DefaultValue = stringRepresentation return p }
go
func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter { p.data.DefaultValue = stringRepresentation return p }
[ "func", "(", "p", "*", "Parameter", ")", "DefaultValue", "(", "stringRepresentation", "string", ")", "*", "Parameter", "{", "p", ".", "data", ".", "DefaultValue", "=", "stringRepresentation", "\n", "return", "p", "\n", "}" ]
// DefaultValue sets the default value field and returns the receiver
[ "DefaultValue", "sets", "the", "default", "value", "field", "and", "returns", "the", "receiver" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L128-L131
146,785
emicklei/go-restful
parameter.go
Description
func (p *Parameter) Description(doc string) *Parameter { p.data.Description = doc return p }
go
func (p *Parameter) Description(doc string) *Parameter { p.data.Description = doc return p }
[ "func", "(", "p", "*", "Parameter", ")", "Description", "(", "doc", "string", ")", "*", "Parameter", "{", "p", ".", "data", ".", "Description", "=", "doc", "\n", "return", "p", "\n", "}" ]
// Description sets the description value field and returns the receiver
[ "Description", "sets", "the", "description", "value", "field", "and", "returns", "the", "receiver" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L134-L137
146,786
emicklei/go-restful
parameter.go
CollectionFormat
func (p *Parameter) CollectionFormat(format CollectionFormat) *Parameter { p.data.CollectionFormat = format.String() return p }
go
func (p *Parameter) CollectionFormat(format CollectionFormat) *Parameter { p.data.CollectionFormat = format.String() return p }
[ "func", "(", "p", "*", "Parameter", ")", "CollectionFormat", "(", "format", "CollectionFormat", ")", "*", "Parameter", "{", "p", ".", "data", ".", "CollectionFormat", "=", "format", ".", "String", "(", ")", "\n", "return", "p", "\n", "}" ]
// CollectionFormat sets the collection format for an array type
[ "CollectionFormat", "sets", "the", "collection", "format", "for", "an", "array", "type" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/parameter.go#L140-L143
146,787
emicklei/go-restful
response.go
NewResponse
func NewResponse(httpWriter http.ResponseWriter) *Response { hijacker, _ := httpWriter.(http.Hijacker) return &Response{ResponseWriter: httpWriter, routeProduces: []string{}, statusCode: http.StatusOK, prettyPrint: PrettyPrintResponses, hijacker: hijacker} }
go
func NewResponse(httpWriter http.ResponseWriter) *Response { hijacker, _ := httpWriter.(http.Hijacker) return &Response{ResponseWriter: httpWriter, routeProduces: []string{}, statusCode: http.StatusOK, prettyPrint: PrettyPrintResponses, hijacker: hijacker} }
[ "func", "NewResponse", "(", "httpWriter", "http", ".", "ResponseWriter", ")", "*", "Response", "{", "hijacker", ",", "_", ":=", "httpWriter", ".", "(", "http", ".", "Hijacker", ")", "\n", "return", "&", "Response", "{", "ResponseWriter", ":", "httpWriter", ",", "routeProduces", ":", "[", "]", "string", "{", "}", ",", "statusCode", ":", "http", ".", "StatusOK", ",", "prettyPrint", ":", "PrettyPrintResponses", ",", "hijacker", ":", "hijacker", "}", "\n", "}" ]
// NewResponse creates a new response based on a http ResponseWriter.
[ "NewResponse", "creates", "a", "new", "response", "based", "on", "a", "http", "ResponseWriter", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L34-L37
146,788
emicklei/go-restful
response.go
Hijack
func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) { if r.hijacker == nil { return nil, nil, errors.New("http.Hijacker not implemented by underlying http.ResponseWriter") } return r.hijacker.Hijack() }
go
func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) { if r.hijacker == nil { return nil, nil, errors.New("http.Hijacker not implemented by underlying http.ResponseWriter") } return r.hijacker.Hijack() }
[ "func", "(", "r", "*", "Response", ")", "Hijack", "(", ")", "(", "net", ".", "Conn", ",", "*", "bufio", ".", "ReadWriter", ",", "error", ")", "{", "if", "r", ".", "hijacker", "==", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "r", ".", "hijacker", ".", "Hijack", "(", ")", "\n", "}" ]
// Hijack implements the http.Hijacker interface. This expands // the Response to fulfill http.Hijacker if the underlying // http.ResponseWriter supports it.
[ "Hijack", "implements", "the", "http", ".", "Hijacker", "interface", ".", "This", "expands", "the", "Response", "to", "fulfill", "http", ".", "Hijacker", "if", "the", "underlying", "http", ".", "ResponseWriter", "supports", "it", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L58-L63
146,789
emicklei/go-restful
response.go
WriteError
func (r *Response) WriteError(httpStatus int, err error) error { r.err = err return r.WriteErrorString(httpStatus, err.Error()) }
go
func (r *Response) WriteError(httpStatus int, err error) error { r.err = err return r.WriteErrorString(httpStatus, err.Error()) }
[ "func", "(", "r", "*", "Response", ")", "WriteError", "(", "httpStatus", "int", ",", "err", "error", ")", "error", "{", "r", ".", "err", "=", "err", "\n", "return", "r", ".", "WriteErrorString", "(", "httpStatus", ",", "err", ".", "Error", "(", ")", ")", "\n", "}" ]
// WriteError write the http status and the error string on the response.
[ "WriteError", "write", "the", "http", "status", "and", "the", "error", "string", "on", "the", "response", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L178-L181
146,790
emicklei/go-restful
response.go
WriteServiceError
func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error { r.err = err return r.WriteHeaderAndEntity(httpStatus, err) }
go
func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error { r.err = err return r.WriteHeaderAndEntity(httpStatus, err) }
[ "func", "(", "r", "*", "Response", ")", "WriteServiceError", "(", "httpStatus", "int", ",", "err", "ServiceError", ")", "error", "{", "r", ".", "err", "=", "err", "\n", "return", "r", ".", "WriteHeaderAndEntity", "(", "httpStatus", ",", "err", ")", "\n", "}" ]
// WriteServiceError is a convenience method for a responding with a status and a ServiceError
[ "WriteServiceError", "is", "a", "convenience", "method", "for", "a", "responding", "with", "a", "status", "and", "a", "ServiceError" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L184-L187
146,791
emicklei/go-restful
response.go
WriteErrorString
func (r *Response) WriteErrorString(httpStatus int, errorReason string) error { if r.err == nil { // if not called from WriteError r.err = errors.New(errorReason) } r.WriteHeader(httpStatus) if _, err := r.Write([]byte(errorReason)); err != nil { return err } return nil }
go
func (r *Response) WriteErrorString(httpStatus int, errorReason string) error { if r.err == nil { // if not called from WriteError r.err = errors.New(errorReason) } r.WriteHeader(httpStatus) if _, err := r.Write([]byte(errorReason)); err != nil { return err } return nil }
[ "func", "(", "r", "*", "Response", ")", "WriteErrorString", "(", "httpStatus", "int", ",", "errorReason", "string", ")", "error", "{", "if", "r", ".", "err", "==", "nil", "{", "// if not called from WriteError", "r", ".", "err", "=", "errors", ".", "New", "(", "errorReason", ")", "\n", "}", "\n", "r", ".", "WriteHeader", "(", "httpStatus", ")", "\n", "if", "_", ",", "err", ":=", "r", ".", "Write", "(", "[", "]", "byte", "(", "errorReason", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// WriteErrorString is a convenience method for an error status with the actual error
[ "WriteErrorString", "is", "a", "convenience", "method", "for", "an", "error", "status", "with", "the", "actual", "error" ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L190-L200
146,792
emicklei/go-restful
response.go
Flush
func (r *Response) Flush() { if f, ok := r.ResponseWriter.(http.Flusher); ok { f.Flush() } else if trace { traceLogger.Printf("ResponseWriter %v doesn't support Flush", r) } }
go
func (r *Response) Flush() { if f, ok := r.ResponseWriter.(http.Flusher); ok { f.Flush() } else if trace { traceLogger.Printf("ResponseWriter %v doesn't support Flush", r) } }
[ "func", "(", "r", "*", "Response", ")", "Flush", "(", ")", "{", "if", "f", ",", "ok", ":=", "r", ".", "ResponseWriter", ".", "(", "http", ".", "Flusher", ")", ";", "ok", "{", "f", ".", "Flush", "(", ")", "\n", "}", "else", "if", "trace", "{", "traceLogger", ".", "Printf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "}" ]
// Flush implements http.Flusher interface, which sends any buffered data to the client.
[ "Flush", "implements", "http", ".", "Flusher", "interface", "which", "sends", "any", "buffered", "data", "to", "the", "client", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L203-L209
146,793
emicklei/go-restful
response.go
WriteHeader
func (r *Response) WriteHeader(httpStatus int) { r.statusCode = httpStatus r.ResponseWriter.WriteHeader(httpStatus) }
go
func (r *Response) WriteHeader(httpStatus int) { r.statusCode = httpStatus r.ResponseWriter.WriteHeader(httpStatus) }
[ "func", "(", "r", "*", "Response", ")", "WriteHeader", "(", "httpStatus", "int", ")", "{", "r", ".", "statusCode", "=", "httpStatus", "\n", "r", ".", "ResponseWriter", ".", "WriteHeader", "(", "httpStatus", ")", "\n", "}" ]
// WriteHeader is overridden to remember the Status Code that has been written. // Changes to the Header of the response have no effect after this.
[ "WriteHeader", "is", "overridden", "to", "remember", "the", "Status", "Code", "that", "has", "been", "written", ".", "Changes", "to", "the", "Header", "of", "the", "response", "have", "no", "effect", "after", "this", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L213-L216
146,794
emicklei/go-restful
response.go
StatusCode
func (r Response) StatusCode() int { if 0 == r.statusCode { // no status code has been written yet; assume OK return http.StatusOK } return r.statusCode }
go
func (r Response) StatusCode() int { if 0 == r.statusCode { // no status code has been written yet; assume OK return http.StatusOK } return r.statusCode }
[ "func", "(", "r", "Response", ")", "StatusCode", "(", ")", "int", "{", "if", "0", "==", "r", ".", "statusCode", "{", "// no status code has been written yet; assume OK", "return", "http", ".", "StatusOK", "\n", "}", "\n", "return", "r", ".", "statusCode", "\n", "}" ]
// StatusCode returns the code that has been written using WriteHeader.
[ "StatusCode", "returns", "the", "code", "that", "has", "been", "written", "using", "WriteHeader", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L219-L225
146,795
emicklei/go-restful
response.go
Write
func (r *Response) Write(bytes []byte) (int, error) { written, err := r.ResponseWriter.Write(bytes) r.contentLength += written return written, err }
go
func (r *Response) Write(bytes []byte) (int, error) { written, err := r.ResponseWriter.Write(bytes) r.contentLength += written return written, err }
[ "func", "(", "r", "*", "Response", ")", "Write", "(", "bytes", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "written", ",", "err", ":=", "r", ".", "ResponseWriter", ".", "Write", "(", "bytes", ")", "\n", "r", ".", "contentLength", "+=", "written", "\n", "return", "written", ",", "err", "\n", "}" ]
// Write writes the data to the connection as part of an HTTP reply. // Write is part of http.ResponseWriter interface.
[ "Write", "writes", "the", "data", "to", "the", "connection", "as", "part", "of", "an", "HTTP", "reply", ".", "Write", "is", "part", "of", "http", ".", "ResponseWriter", "interface", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/response.go#L229-L233
146,796
emicklei/go-restful
mime.go
insertMime
func insertMime(l []mime, e mime) []mime { for i, each := range l { // if current mime has lower quality then insert before if e.quality > each.quality { left := append([]mime{}, l[0:i]...) return append(append(left, e), l[i:]...) } } return append(l, e) }
go
func insertMime(l []mime, e mime) []mime { for i, each := range l { // if current mime has lower quality then insert before if e.quality > each.quality { left := append([]mime{}, l[0:i]...) return append(append(left, e), l[i:]...) } } return append(l, e) }
[ "func", "insertMime", "(", "l", "[", "]", "mime", ",", "e", "mime", ")", "[", "]", "mime", "{", "for", "i", ",", "each", ":=", "range", "l", "{", "// if current mime has lower quality then insert before", "if", "e", ".", "quality", ">", "each", ".", "quality", "{", "left", ":=", "append", "(", "[", "]", "mime", "{", "}", ",", "l", "[", "0", ":", "i", "]", "...", ")", "\n", "return", "append", "(", "append", "(", "left", ",", "e", ")", ",", "l", "[", "i", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "return", "append", "(", "l", ",", "e", ")", "\n", "}" ]
// insertMime adds a mime to a list and keeps it sorted by quality.
[ "insertMime", "adds", "a", "mime", "to", "a", "list", "and", "keeps", "it", "sorted", "by", "quality", "." ]
d2b8501d30f1b2c552dafdb21e3434bbafdaa124
https://github.com/emicklei/go-restful/blob/d2b8501d30f1b2c552dafdb21e3434bbafdaa124/mime.go#L14-L23
146,797
davecgh/go-spew
spew/bypass.go
flagField
func flagField(v *reflect.Value) *flag { return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) }
go
func flagField(v *reflect.Value) *flag { return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) }
[ "func", "flagField", "(", "v", "*", "reflect", ".", "Value", ")", "*", "flag", "{", "return", "(", "*", "flag", ")", "(", "unsafe", ".", "Pointer", "(", "uintptr", "(", "unsafe", ".", "Pointer", "(", "v", ")", ")", "+", "flagValOffset", ")", ")", "\n", "}" ]
// flagField returns a pointer to the flag field of a reflect.Value.
[ "flagField", "returns", "a", "pointer", "to", "the", "flag", "field", "of", "a", "reflect", ".", "Value", "." ]
d8f796af33cc11cb798c1aaeb27a4ebc5099927d
https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/bypass.go#L80-L82
146,798
davecgh/go-spew
spew/bypass.go
init
func init() { field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") if !ok { panic("reflect.Value has no flag field") } if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { panic("reflect.Value flag field has changed kind") } type t0 int var t struct { A t0 // t0 will have flagEmbedRO set. t0 // a will have flagStickyRO set a t0 } vA := reflect.ValueOf(t).FieldByName("A") va := reflect.ValueOf(t).FieldByName("a") vt0 := reflect.ValueOf(t).FieldByName("t0") // Infer flagRO from the difference between the flags // for the (otherwise identical) fields in t. flagPublic := *flagField(&vA) flagWithRO := *flagField(&va) | *flagField(&vt0) flagRO = flagPublic ^ flagWithRO // Infer flagAddr from the difference between a value // taken from a pointer and not. vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") flagNoPtr := *flagField(&vA) flagPtr := *flagField(&vPtrA) flagAddr = flagNoPtr ^ flagPtr // Check that the inferred flags tally with one of the known versions. for _, f := range okFlags { if flagRO == f.ro && flagAddr == f.addr { return } } panic("reflect.Value read-only flag has changed semantics") }
go
func init() { field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") if !ok { panic("reflect.Value has no flag field") } if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { panic("reflect.Value flag field has changed kind") } type t0 int var t struct { A t0 // t0 will have flagEmbedRO set. t0 // a will have flagStickyRO set a t0 } vA := reflect.ValueOf(t).FieldByName("A") va := reflect.ValueOf(t).FieldByName("a") vt0 := reflect.ValueOf(t).FieldByName("t0") // Infer flagRO from the difference between the flags // for the (otherwise identical) fields in t. flagPublic := *flagField(&vA) flagWithRO := *flagField(&va) | *flagField(&vt0) flagRO = flagPublic ^ flagWithRO // Infer flagAddr from the difference between a value // taken from a pointer and not. vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") flagNoPtr := *flagField(&vA) flagPtr := *flagField(&vPtrA) flagAddr = flagNoPtr ^ flagPtr // Check that the inferred flags tally with one of the known versions. for _, f := range okFlags { if flagRO == f.ro && flagAddr == f.addr { return } } panic("reflect.Value read-only flag has changed semantics") }
[ "func", "init", "(", ")", "{", "field", ",", "ok", ":=", "reflect", ".", "TypeOf", "(", "reflect", ".", "Value", "{", "}", ")", ".", "FieldByName", "(", "\"", "\"", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "field", ".", "Type", ".", "Kind", "(", ")", "!=", "reflect", ".", "TypeOf", "(", "flag", "(", "0", ")", ")", ".", "Kind", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "type", "t0", "int", "\n", "var", "t", "struct", "{", "A", "t0", "\n", "// t0 will have flagEmbedRO set.", "t0", "\n", "// a will have flagStickyRO set", "a", "t0", "\n", "}", "\n", "vA", ":=", "reflect", ".", "ValueOf", "(", "t", ")", ".", "FieldByName", "(", "\"", "\"", ")", "\n", "va", ":=", "reflect", ".", "ValueOf", "(", "t", ")", ".", "FieldByName", "(", "\"", "\"", ")", "\n", "vt0", ":=", "reflect", ".", "ValueOf", "(", "t", ")", ".", "FieldByName", "(", "\"", "\"", ")", "\n\n", "// Infer flagRO from the difference between the flags", "// for the (otherwise identical) fields in t.", "flagPublic", ":=", "*", "flagField", "(", "&", "vA", ")", "\n", "flagWithRO", ":=", "*", "flagField", "(", "&", "va", ")", "|", "*", "flagField", "(", "&", "vt0", ")", "\n", "flagRO", "=", "flagPublic", "^", "flagWithRO", "\n\n", "// Infer flagAddr from the difference between a value", "// taken from a pointer and not.", "vPtrA", ":=", "reflect", ".", "ValueOf", "(", "&", "t", ")", ".", "Elem", "(", ")", ".", "FieldByName", "(", "\"", "\"", ")", "\n", "flagNoPtr", ":=", "*", "flagField", "(", "&", "vA", ")", "\n", "flagPtr", ":=", "*", "flagField", "(", "&", "vPtrA", ")", "\n", "flagAddr", "=", "flagNoPtr", "^", "flagPtr", "\n\n", "// Check that the inferred flags tally with one of the known versions.", "for", "_", ",", "f", ":=", "range", "okFlags", "{", "if", "flagRO", "==", "f", ".", "ro", "&&", "flagAddr", "==", "f", ".", "addr", "{", "return", "\n", "}", "\n", "}", "\n", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// Sanity checks against future reflect package changes // to the type or semantics of the Value.flag field.
[ "Sanity", "checks", "against", "future", "reflect", "package", "changes", "to", "the", "type", "or", "semantics", "of", "the", "Value", ".", "flag", "field", "." ]
d8f796af33cc11cb798c1aaeb27a4ebc5099927d
https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/bypass.go#L105-L145
146,799
davecgh/go-spew
spew/format.go
buildDefaultFormat
func (f *formatState) buildDefaultFormat() (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } buf.WriteRune('v') format = buf.String() return format }
go
func (f *formatState) buildDefaultFormat() (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } buf.WriteRune('v') format = buf.String() return format }
[ "func", "(", "f", "*", "formatState", ")", "buildDefaultFormat", "(", ")", "(", "format", "string", ")", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "percentBytes", ")", "\n\n", "for", "_", ",", "flag", ":=", "range", "supportedFlags", "{", "if", "f", ".", "fs", ".", "Flag", "(", "int", "(", "flag", ")", ")", "{", "buf", ".", "WriteRune", "(", "flag", ")", "\n", "}", "\n", "}", "\n\n", "buf", ".", "WriteRune", "(", "'v'", ")", "\n\n", "format", "=", "buf", ".", "String", "(", ")", "\n", "return", "format", "\n", "}" ]
// buildDefaultFormat recreates the original format string without precision // and width information to pass in to fmt.Sprintf in the case of an // unrecognized type. Unless new types are added to the language, this // function won't ever be called.
[ "buildDefaultFormat", "recreates", "the", "original", "format", "string", "without", "precision", "and", "width", "information", "to", "pass", "in", "to", "fmt", ".", "Sprintf", "in", "the", "case", "of", "an", "unrecognized", "type", ".", "Unless", "new", "types", "are", "added", "to", "the", "language", "this", "function", "won", "t", "ever", "be", "called", "." ]
d8f796af33cc11cb798c1aaeb27a4ebc5099927d
https://github.com/davecgh/go-spew/blob/d8f796af33cc11cb798c1aaeb27a4ebc5099927d/spew/format.go#L47-L60