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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
15,600
LindsayBradford/go-dbf
godbf/dbftable.go
AddNewRecord
func (dt *DbfTable) AddNewRecord() (newRecordNumber int) { if dt.dataEntryStarted == false { dt.dataEntryStarted = true } newRecord := make([]byte, dt.lengthOfEachRecord) dt.dataStore = appendSlice(dt.dataStore, newRecord) // since row numbers are "0" based first we set newRecordNumber // and then increment number of records in dbase table newRecordNumber = int(dt.numberOfRecords) //fmt.Printf("Number of rows before:%d\n", dt.numberOfRecords) dt.numberOfRecords++ s := uint32ToBytes(dt.numberOfRecords) dt.dataStore[4] = s[0] dt.dataStore[5] = s[1] dt.dataStore[6] = s[2] dt.dataStore[7] = s[3] //fmt.Printf("Number of rows after:%d\n", dt.numberOfRecords) return newRecordNumber }
go
func (dt *DbfTable) AddNewRecord() (newRecordNumber int) { if dt.dataEntryStarted == false { dt.dataEntryStarted = true } newRecord := make([]byte, dt.lengthOfEachRecord) dt.dataStore = appendSlice(dt.dataStore, newRecord) // since row numbers are "0" based first we set newRecordNumber // and then increment number of records in dbase table newRecordNumber = int(dt.numberOfRecords) //fmt.Printf("Number of rows before:%d\n", dt.numberOfRecords) dt.numberOfRecords++ s := uint32ToBytes(dt.numberOfRecords) dt.dataStore[4] = s[0] dt.dataStore[5] = s[1] dt.dataStore[6] = s[2] dt.dataStore[7] = s[3] //fmt.Printf("Number of rows after:%d\n", dt.numberOfRecords) return newRecordNumber }
[ "func", "(", "dt", "*", "DbfTable", ")", "AddNewRecord", "(", ")", "(", "newRecordNumber", "int", ")", "{", "if", "dt", ".", "dataEntryStarted", "==", "false", "{", "dt", ".", "dataEntryStarted", "=", "true", "\n", "}", "\n\n", "newRecord", ":=", "make", "(", "[", "]", "byte", ",", "dt", ".", "lengthOfEachRecord", ")", "\n", "dt", ".", "dataStore", "=", "appendSlice", "(", "dt", ".", "dataStore", ",", "newRecord", ")", "\n\n", "// since row numbers are \"0\" based first we set newRecordNumber", "// and then increment number of records in dbase table", "newRecordNumber", "=", "int", "(", "dt", ".", "numberOfRecords", ")", "\n\n", "//fmt.Printf(\"Number of rows before:%d\\n\", dt.numberOfRecords)", "dt", ".", "numberOfRecords", "++", "\n", "s", ":=", "uint32ToBytes", "(", "dt", ".", "numberOfRecords", ")", "\n", "dt", ".", "dataStore", "[", "4", "]", "=", "s", "[", "0", "]", "\n", "dt", ".", "dataStore", "[", "5", "]", "=", "s", "[", "1", "]", "\n", "dt", ".", "dataStore", "[", "6", "]", "=", "s", "[", "2", "]", "\n", "dt", ".", "dataStore", "[", "7", "]", "=", "s", "[", "3", "]", "\n", "//fmt.Printf(\"Number of rows after:%d\\n\", dt.numberOfRecords)", "return", "newRecordNumber", "\n", "}" ]
// AddNewRecord adds a new empty record to the table, and returns the index number of the record.
[ "AddNewRecord", "adds", "a", "new", "empty", "record", "to", "the", "table", "and", "returns", "the", "index", "number", "of", "the", "record", "." ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L324-L347
15,601
LindsayBradford/go-dbf
godbf/dbftable.go
SetFieldValueByName
func (dt *DbfTable) SetFieldValueByName(row int, fieldName string, value string) (err error) { if fieldIndex, found := dt.fieldMap[fieldName]; found { return dt.SetFieldValue(row, fieldIndex, value) } return errors.New("Field name \"" + fieldName + "\" does not exist") }
go
func (dt *DbfTable) SetFieldValueByName(row int, fieldName string, value string) (err error) { if fieldIndex, found := dt.fieldMap[fieldName]; found { return dt.SetFieldValue(row, fieldIndex, value) } return errors.New("Field name \"" + fieldName + "\" does not exist") }
[ "func", "(", "dt", "*", "DbfTable", ")", "SetFieldValueByName", "(", "row", "int", ",", "fieldName", "string", ",", "value", "string", ")", "(", "err", "error", ")", "{", "if", "fieldIndex", ",", "found", ":=", "dt", ".", "fieldMap", "[", "fieldName", "]", ";", "found", "{", "return", "dt", ".", "SetFieldValue", "(", "row", ",", "fieldIndex", ",", "value", ")", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\\\"", "\"", "+", "fieldName", "+", "\"", "\\\"", "\"", ")", "\n", "}" ]
// SetFieldValueByName sets the value for the given row and field name as specified // If the field name does not exist, or the value is incompatible with the field's type, an error is returned.
[ "SetFieldValueByName", "sets", "the", "value", "for", "the", "given", "row", "and", "field", "name", "as", "specified", "If", "the", "field", "name", "does", "not", "exist", "or", "the", "value", "is", "incompatible", "with", "the", "field", "s", "type", "an", "error", "is", "returned", "." ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L356-L361
15,602
LindsayBradford/go-dbf
godbf/dbftable.go
SetFieldValue
func (dt *DbfTable) SetFieldValue(row int, fieldIndex int, value string) (err error) { b := []byte(dt.encoder.ConvertString(value)) fieldLength := int(dt.fields[fieldIndex].length) //DEBUG //fmt.Printf("dt.numberOfBytesInHeader=%v\n\n", dt.numberOfBytesInHeader) //fmt.Printf("dt.lengthOfEachRecord=%v\n\n", dt.lengthOfEachRecord) // locate the offset of the field in DbfTable dataStore offset := int(dt.numberOfBytesInHeader) lengthOfRecord := int(dt.lengthOfEachRecord) offset = offset + (row * lengthOfRecord) recordOffset := 1 for i := 0; i < len(dt.fields); i++ { if i == fieldIndex { break } else { recordOffset += int(dt.fields[i].length) } } dt.fillFieldWithBlanks(fieldLength, offset, recordOffset) // write new value switch dt.fields[fieldIndex].fieldType { case Character, Logical, Date: for i := 0; i < len(b) && i < fieldLength; i++ { dt.dataStore[offset+recordOffset+i] = b[i] } case Float, Numeric: for i := 0; i < fieldLength; i++ { // fmt.Printf("i:%v\n", i) if i < len(b) { dt.dataStore[offset+recordOffset+(fieldLength-i-1)] = b[(len(b)-1)-i] } else { break } } } return //fmt.Printf("field value:%#v\n", []byte(value)) //fmt.Printf("field index:%#v\n", fieldIndex) //fmt.Printf("field fixedFieldLength:%v\n", dt.Fields[fieldIndex].fixedFieldLength) //fmt.Printf("string to byte:%#v\n", b) }
go
func (dt *DbfTable) SetFieldValue(row int, fieldIndex int, value string) (err error) { b := []byte(dt.encoder.ConvertString(value)) fieldLength := int(dt.fields[fieldIndex].length) //DEBUG //fmt.Printf("dt.numberOfBytesInHeader=%v\n\n", dt.numberOfBytesInHeader) //fmt.Printf("dt.lengthOfEachRecord=%v\n\n", dt.lengthOfEachRecord) // locate the offset of the field in DbfTable dataStore offset := int(dt.numberOfBytesInHeader) lengthOfRecord := int(dt.lengthOfEachRecord) offset = offset + (row * lengthOfRecord) recordOffset := 1 for i := 0; i < len(dt.fields); i++ { if i == fieldIndex { break } else { recordOffset += int(dt.fields[i].length) } } dt.fillFieldWithBlanks(fieldLength, offset, recordOffset) // write new value switch dt.fields[fieldIndex].fieldType { case Character, Logical, Date: for i := 0; i < len(b) && i < fieldLength; i++ { dt.dataStore[offset+recordOffset+i] = b[i] } case Float, Numeric: for i := 0; i < fieldLength; i++ { // fmt.Printf("i:%v\n", i) if i < len(b) { dt.dataStore[offset+recordOffset+(fieldLength-i-1)] = b[(len(b)-1)-i] } else { break } } } return //fmt.Printf("field value:%#v\n", []byte(value)) //fmt.Printf("field index:%#v\n", fieldIndex) //fmt.Printf("field fixedFieldLength:%v\n", dt.Fields[fieldIndex].fixedFieldLength) //fmt.Printf("string to byte:%#v\n", b) }
[ "func", "(", "dt", "*", "DbfTable", ")", "SetFieldValue", "(", "row", "int", ",", "fieldIndex", "int", ",", "value", "string", ")", "(", "err", "error", ")", "{", "b", ":=", "[", "]", "byte", "(", "dt", ".", "encoder", ".", "ConvertString", "(", "value", ")", ")", "\n\n", "fieldLength", ":=", "int", "(", "dt", ".", "fields", "[", "fieldIndex", "]", ".", "length", ")", "\n\n", "//DEBUG", "//fmt.Printf(\"dt.numberOfBytesInHeader=%v\\n\\n\", dt.numberOfBytesInHeader)", "//fmt.Printf(\"dt.lengthOfEachRecord=%v\\n\\n\", dt.lengthOfEachRecord)", "// locate the offset of the field in DbfTable dataStore", "offset", ":=", "int", "(", "dt", ".", "numberOfBytesInHeader", ")", "\n", "lengthOfRecord", ":=", "int", "(", "dt", ".", "lengthOfEachRecord", ")", "\n\n", "offset", "=", "offset", "+", "(", "row", "*", "lengthOfRecord", ")", "\n\n", "recordOffset", ":=", "1", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "dt", ".", "fields", ")", ";", "i", "++", "{", "if", "i", "==", "fieldIndex", "{", "break", "\n", "}", "else", "{", "recordOffset", "+=", "int", "(", "dt", ".", "fields", "[", "i", "]", ".", "length", ")", "\n", "}", "\n", "}", "\n\n", "dt", ".", "fillFieldWithBlanks", "(", "fieldLength", ",", "offset", ",", "recordOffset", ")", "\n\n", "// write new value", "switch", "dt", ".", "fields", "[", "fieldIndex", "]", ".", "fieldType", "{", "case", "Character", ",", "Logical", ",", "Date", ":", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ")", "&&", "i", "<", "fieldLength", ";", "i", "++", "{", "dt", ".", "dataStore", "[", "offset", "+", "recordOffset", "+", "i", "]", "=", "b", "[", "i", "]", "\n", "}", "\n", "case", "Float", ",", "Numeric", ":", "for", "i", ":=", "0", ";", "i", "<", "fieldLength", ";", "i", "++", "{", "// fmt.Printf(\"i:%v\\n\", i)", "if", "i", "<", "len", "(", "b", ")", "{", "dt", ".", "dataStore", "[", "offset", "+", "recordOffset", "+", "(", "fieldLength", "-", "i", "-", "1", ")", "]", "=", "b", "[", "(", "len", "(", "b", ")", "-", "1", ")", "-", "i", "]", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "\n\n", "//fmt.Printf(\"field value:%#v\\n\", []byte(value))", "//fmt.Printf(\"field index:%#v\\n\", fieldIndex)", "//fmt.Printf(\"field fixedFieldLength:%v\\n\", dt.Fields[fieldIndex].fixedFieldLength)", "//fmt.Printf(\"string to byte:%#v\\n\", b)", "}" ]
// SetFieldValue sets the value for the given row and field index as specified // If the field index is invalid, or the value is incompatible with the field's type, an error is returned.
[ "SetFieldValue", "sets", "the", "value", "for", "the", "given", "row", "and", "field", "index", "as", "specified", "If", "the", "field", "index", "is", "invalid", "or", "the", "value", "is", "incompatible", "with", "the", "field", "s", "type", "an", "error", "is", "returned", "." ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L365-L417
15,603
LindsayBradford/go-dbf
godbf/dbftable.go
FieldValue
func (dt *DbfTable) FieldValue(row int, fieldIndex int) (value string) { offset := int(dt.numberOfBytesInHeader) lengthOfRecord := int(dt.lengthOfEachRecord) offset = offset + (row * lengthOfRecord) recordOffset := 1 for i := 0; i < len(dt.fields); i++ { if i == fieldIndex { break } else { recordOffset += int(dt.fields[i].length) } } temp := dt.dataStore[(offset + recordOffset):((offset + recordOffset) + int(dt.fields[fieldIndex].length))] enforceBlankPadding(temp) s := dt.decoder.ConvertString(string(temp)) //fmt.Printf("utf-8 value:[%#v] original value:[%#v]\n", s, string(temp)) value = strings.TrimSpace(s) //fmt.Printf("raw value:[%#v]\n", dt.dataStore[(offset + recordOffset):((offset + recordOffset) + int(dt.Fields[fieldIndex].fixedFieldLength))]) //fmt.Printf("utf-8 value:[%#v]\n", []byte(s)) //value = string(dt.dataStore[(offset + recordOffset):((offset + recordOffset) + int(dt.Fields[fieldIndex].fixedFieldLength))]) return }
go
func (dt *DbfTable) FieldValue(row int, fieldIndex int) (value string) { offset := int(dt.numberOfBytesInHeader) lengthOfRecord := int(dt.lengthOfEachRecord) offset = offset + (row * lengthOfRecord) recordOffset := 1 for i := 0; i < len(dt.fields); i++ { if i == fieldIndex { break } else { recordOffset += int(dt.fields[i].length) } } temp := dt.dataStore[(offset + recordOffset):((offset + recordOffset) + int(dt.fields[fieldIndex].length))] enforceBlankPadding(temp) s := dt.decoder.ConvertString(string(temp)) //fmt.Printf("utf-8 value:[%#v] original value:[%#v]\n", s, string(temp)) value = strings.TrimSpace(s) //fmt.Printf("raw value:[%#v]\n", dt.dataStore[(offset + recordOffset):((offset + recordOffset) + int(dt.Fields[fieldIndex].fixedFieldLength))]) //fmt.Printf("utf-8 value:[%#v]\n", []byte(s)) //value = string(dt.dataStore[(offset + recordOffset):((offset + recordOffset) + int(dt.Fields[fieldIndex].fixedFieldLength))]) return }
[ "func", "(", "dt", "*", "DbfTable", ")", "FieldValue", "(", "row", "int", ",", "fieldIndex", "int", ")", "(", "value", "string", ")", "{", "offset", ":=", "int", "(", "dt", ".", "numberOfBytesInHeader", ")", "\n", "lengthOfRecord", ":=", "int", "(", "dt", ".", "lengthOfEachRecord", ")", "\n\n", "offset", "=", "offset", "+", "(", "row", "*", "lengthOfRecord", ")", "\n\n", "recordOffset", ":=", "1", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "dt", ".", "fields", ")", ";", "i", "++", "{", "if", "i", "==", "fieldIndex", "{", "break", "\n", "}", "else", "{", "recordOffset", "+=", "int", "(", "dt", ".", "fields", "[", "i", "]", ".", "length", ")", "\n", "}", "\n", "}", "\n\n", "temp", ":=", "dt", ".", "dataStore", "[", "(", "offset", "+", "recordOffset", ")", ":", "(", "(", "offset", "+", "recordOffset", ")", "+", "int", "(", "dt", ".", "fields", "[", "fieldIndex", "]", ".", "length", ")", ")", "]", "\n\n", "enforceBlankPadding", "(", "temp", ")", "\n\n", "s", ":=", "dt", ".", "decoder", ".", "ConvertString", "(", "string", "(", "temp", ")", ")", "\n", "//fmt.Printf(\"utf-8 value:[%#v] original value:[%#v]\\n\", s, string(temp))", "value", "=", "strings", ".", "TrimSpace", "(", "s", ")", "\n\n", "//fmt.Printf(\"raw value:[%#v]\\n\", dt.dataStore[(offset + recordOffset):((offset + recordOffset) + int(dt.Fields[fieldIndex].fixedFieldLength))])", "//fmt.Printf(\"utf-8 value:[%#v]\\n\", []byte(s))", "//value = string(dt.dataStore[(offset + recordOffset):((offset + recordOffset) + int(dt.Fields[fieldIndex].fixedFieldLength))])", "return", "\n", "}" ]
//FieldValue returns the content for the record at the given row and field index as a string // If the row or field index is invalid, an error is returned .
[ "FieldValue", "returns", "the", "content", "for", "the", "record", "at", "the", "given", "row", "and", "field", "index", "as", "a", "string", "If", "the", "row", "or", "field", "index", "is", "invalid", "an", "error", "is", "returned", "." ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L427-L457
15,604
LindsayBradford/go-dbf
godbf/dbftable.go
Float64FieldValueByName
func (dt *DbfTable) Float64FieldValueByName(row int, fieldName string) (value float64, err error) { valueAsString, err := dt.FieldValueByName(row, fieldName) return strconv.ParseFloat(valueAsString, 64) }
go
func (dt *DbfTable) Float64FieldValueByName(row int, fieldName string) (value float64, err error) { valueAsString, err := dt.FieldValueByName(row, fieldName) return strconv.ParseFloat(valueAsString, 64) }
[ "func", "(", "dt", "*", "DbfTable", ")", "Float64FieldValueByName", "(", "row", "int", ",", "fieldName", "string", ")", "(", "value", "float64", ",", "err", "error", ")", "{", "valueAsString", ",", "err", ":=", "dt", ".", "FieldValueByName", "(", "row", ",", "fieldName", ")", "\n", "return", "strconv", ".", "ParseFloat", "(", "valueAsString", ",", "64", ")", "\n", "}" ]
// Float64FieldValueByName returns the value of a field given row number and name provided as a float64
[ "Float64FieldValueByName", "returns", "the", "value", "of", "a", "field", "given", "row", "number", "and", "name", "provided", "as", "a", "float64" ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L470-L473
15,605
LindsayBradford/go-dbf
godbf/dbftable.go
Int64FieldValueByName
func (dt *DbfTable) Int64FieldValueByName(row int, fieldName string) (value int64, err error) { valueAsString, err := dt.FieldValueByName(row, fieldName) return strconv.ParseInt(valueAsString, 0, 64) }
go
func (dt *DbfTable) Int64FieldValueByName(row int, fieldName string) (value int64, err error) { valueAsString, err := dt.FieldValueByName(row, fieldName) return strconv.ParseInt(valueAsString, 0, 64) }
[ "func", "(", "dt", "*", "DbfTable", ")", "Int64FieldValueByName", "(", "row", "int", ",", "fieldName", "string", ")", "(", "value", "int64", ",", "err", "error", ")", "{", "valueAsString", ",", "err", ":=", "dt", ".", "FieldValueByName", "(", "row", ",", "fieldName", ")", "\n", "return", "strconv", ".", "ParseInt", "(", "valueAsString", ",", "0", ",", "64", ")", "\n", "}" ]
// Int64FieldValueByName returns the value of a field given row number and name provided as an int64
[ "Int64FieldValueByName", "returns", "the", "value", "of", "a", "field", "given", "row", "number", "and", "name", "provided", "as", "an", "int64" ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L476-L479
15,606
LindsayBradford/go-dbf
godbf/dbftable.go
FieldValueByName
func (dt *DbfTable) FieldValueByName(row int, fieldName string) (value string, err error) { if fieldIndex, entryFound := dt.fieldMap[fieldName]; entryFound { return dt.FieldValue(row, fieldIndex), err } err = errors.New("Field name \"" + fieldName + "\" does not exist") return }
go
func (dt *DbfTable) FieldValueByName(row int, fieldName string) (value string, err error) { if fieldIndex, entryFound := dt.fieldMap[fieldName]; entryFound { return dt.FieldValue(row, fieldIndex), err } err = errors.New("Field name \"" + fieldName + "\" does not exist") return }
[ "func", "(", "dt", "*", "DbfTable", ")", "FieldValueByName", "(", "row", "int", ",", "fieldName", "string", ")", "(", "value", "string", ",", "err", "error", ")", "{", "if", "fieldIndex", ",", "entryFound", ":=", "dt", ".", "fieldMap", "[", "fieldName", "]", ";", "entryFound", "{", "return", "dt", ".", "FieldValue", "(", "row", ",", "fieldIndex", ")", ",", "err", "\n", "}", "\n", "err", "=", "errors", ".", "New", "(", "\"", "\\\"", "\"", "+", "fieldName", "+", "\"", "\\\"", "\"", ")", "\n", "return", "\n", "}" ]
// FieldValueByName returns the value of a field given row number and name provided
[ "FieldValueByName", "returns", "the", "value", "of", "a", "field", "given", "row", "number", "and", "name", "provided" ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L482-L488
15,607
LindsayBradford/go-dbf
godbf/dbftable.go
RowIsDeleted
func (dt *DbfTable) RowIsDeleted(row int) bool { offset := int(dt.numberOfBytesInHeader) lengthOfRecord := int(dt.lengthOfEachRecord) offset = offset + (row * lengthOfRecord) return dt.dataStore[offset:(offset + 1)][0] == 0x2A }
go
func (dt *DbfTable) RowIsDeleted(row int) bool { offset := int(dt.numberOfBytesInHeader) lengthOfRecord := int(dt.lengthOfEachRecord) offset = offset + (row * lengthOfRecord) return dt.dataStore[offset:(offset + 1)][0] == 0x2A }
[ "func", "(", "dt", "*", "DbfTable", ")", "RowIsDeleted", "(", "row", "int", ")", "bool", "{", "offset", ":=", "int", "(", "dt", ".", "numberOfBytesInHeader", ")", "\n", "lengthOfRecord", ":=", "int", "(", "dt", ".", "lengthOfEachRecord", ")", "\n", "offset", "=", "offset", "+", "(", "row", "*", "lengthOfRecord", ")", "\n", "return", "dt", ".", "dataStore", "[", "offset", ":", "(", "offset", "+", "1", ")", "]", "[", "0", "]", "==", "0x2A", "\n", "}" ]
//RowIsDeleted returns whether a row has marked as deleted
[ "RowIsDeleted", "returns", "whether", "a", "row", "has", "marked", "as", "deleted" ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L491-L496
15,608
LindsayBradford/go-dbf
godbf/dbftable.go
GetRowAsSlice
func (dt *DbfTable) GetRowAsSlice(row int) []string { s := make([]string, len(dt.Fields())) for i := 0; i < len(dt.Fields()); i++ { s[i] = dt.FieldValue(row, i) } return s }
go
func (dt *DbfTable) GetRowAsSlice(row int) []string { s := make([]string, len(dt.Fields())) for i := 0; i < len(dt.Fields()); i++ { s[i] = dt.FieldValue(row, i) } return s }
[ "func", "(", "dt", "*", "DbfTable", ")", "GetRowAsSlice", "(", "row", "int", ")", "[", "]", "string", "{", "s", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "dt", ".", "Fields", "(", ")", ")", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "dt", ".", "Fields", "(", ")", ")", ";", "i", "++", "{", "s", "[", "i", "]", "=", "dt", ".", "FieldValue", "(", "row", ",", "i", ")", "\n", "}", "\n\n", "return", "s", "\n", "}" ]
// GetRowAsSlice return the record values for the row specified as a string slice
[ "GetRowAsSlice", "return", "the", "record", "values", "for", "the", "row", "specified", "as", "a", "string", "slice" ]
5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f
https://github.com/LindsayBradford/go-dbf/blob/5f7a16f88561c4d09bd4e74d6c3d1f95e074de3f/godbf/dbftable.go#L499-L508
15,609
sourcegraph/syntaxhighlight
highlight.go
Class
func (c HTMLConfig) Class(kind Kind) string { switch kind { case String: return c.String case Keyword: return c.Keyword case Comment: return c.Comment case Type: return c.Type case Literal: return c.Literal case Punctuation: return c.Punctuation case Plaintext: return c.Plaintext case Tag: return c.Tag case HTMLTag: return c.HTMLTag case HTMLAttrName: return c.HTMLAttrName case HTMLAttrValue: return c.HTMLAttrValue case Decimal: return c.Decimal } return "" }
go
func (c HTMLConfig) Class(kind Kind) string { switch kind { case String: return c.String case Keyword: return c.Keyword case Comment: return c.Comment case Type: return c.Type case Literal: return c.Literal case Punctuation: return c.Punctuation case Plaintext: return c.Plaintext case Tag: return c.Tag case HTMLTag: return c.HTMLTag case HTMLAttrName: return c.HTMLAttrName case HTMLAttrValue: return c.HTMLAttrValue case Decimal: return c.Decimal } return "" }
[ "func", "(", "c", "HTMLConfig", ")", "Class", "(", "kind", "Kind", ")", "string", "{", "switch", "kind", "{", "case", "String", ":", "return", "c", ".", "String", "\n", "case", "Keyword", ":", "return", "c", ".", "Keyword", "\n", "case", "Comment", ":", "return", "c", ".", "Comment", "\n", "case", "Type", ":", "return", "c", ".", "Type", "\n", "case", "Literal", ":", "return", "c", ".", "Literal", "\n", "case", "Punctuation", ":", "return", "c", ".", "Punctuation", "\n", "case", "Plaintext", ":", "return", "c", ".", "Plaintext", "\n", "case", "Tag", ":", "return", "c", ".", "Tag", "\n", "case", "HTMLTag", ":", "return", "c", ".", "HTMLTag", "\n", "case", "HTMLAttrName", ":", "return", "c", ".", "HTMLAttrName", "\n", "case", "HTMLAttrValue", ":", "return", "c", ".", "HTMLAttrValue", "\n", "case", "Decimal", ":", "return", "c", ".", "Decimal", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Class returns the set class for a given token Kind.
[ "Class", "returns", "the", "set", "class", "for", "a", "given", "token", "Kind", "." ]
bd320f5d308e1a3c4314c678d8227a0d72574ae7
https://github.com/sourcegraph/syntaxhighlight/blob/bd320f5d308e1a3c4314c678d8227a0d72574ae7/highlight.go#L72-L100
15,610
sourcegraph/syntaxhighlight
highlight.go
NewScannerReader
func NewScannerReader(src io.Reader) *scanner.Scanner { var s scanner.Scanner s.Init(src) s.Error = func(_ *scanner.Scanner, _ string) {} s.Whitespace = 0 s.Mode = s.Mode ^ scanner.SkipComments return &s }
go
func NewScannerReader(src io.Reader) *scanner.Scanner { var s scanner.Scanner s.Init(src) s.Error = func(_ *scanner.Scanner, _ string) {} s.Whitespace = 0 s.Mode = s.Mode ^ scanner.SkipComments return &s }
[ "func", "NewScannerReader", "(", "src", "io", ".", "Reader", ")", "*", "scanner", ".", "Scanner", "{", "var", "s", "scanner", ".", "Scanner", "\n", "s", ".", "Init", "(", "src", ")", "\n", "s", ".", "Error", "=", "func", "(", "_", "*", "scanner", ".", "Scanner", ",", "_", "string", ")", "{", "}", "\n", "s", ".", "Whitespace", "=", "0", "\n", "s", ".", "Mode", "=", "s", ".", "Mode", "^", "scanner", ".", "SkipComments", "\n", "return", "&", "s", "\n", "}" ]
// NewScannerReader takes a reader src and creates a Scanner.
[ "NewScannerReader", "takes", "a", "reader", "src", "and", "creates", "a", "Scanner", "." ]
bd320f5d308e1a3c4314c678d8227a0d72574ae7
https://github.com/sourcegraph/syntaxhighlight/blob/bd320f5d308e1a3c4314c678d8227a0d72574ae7/highlight.go#L265-L272
15,611
istio/glog
glog.go
V
func V(level Level) Verbose { return Verbose(zap.L().Core().Enabled(zap.DebugLevel)) }
go
func V(level Level) Verbose { return Verbose(zap.L().Core().Enabled(zap.DebugLevel)) }
[ "func", "V", "(", "level", "Level", ")", "Verbose", "{", "return", "Verbose", "(", "zap", ".", "L", "(", ")", ".", "Core", "(", ")", ".", "Enabled", "(", "zap", ".", "DebugLevel", ")", ")", "\n", "}" ]
// V is a shim
[ "V", "is", "a", "shim" ]
d7cfb6fa2ccda15565f68f204d68907c80a5c977
https://github.com/istio/glog/blob/d7cfb6fa2ccda15565f68f204d68907c80a5c977/glog.go#L42-L44
15,612
istio/glog
glog.go
Infof
func (v Verbose) Infof(format string, args ...interface{}) { zap.S().Debugf(format, args...) }
go
func (v Verbose) Infof(format string, args ...interface{}) { zap.S().Debugf(format, args...) }
[ "func", "(", "v", "Verbose", ")", "Infof", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "zap", ".", "S", "(", ")", ".", "Debugf", "(", "format", ",", "args", "...", ")", "\n", "}" ]
// Infof is a shim
[ "Infof", "is", "a", "shim" ]
d7cfb6fa2ccda15565f68f204d68907c80a5c977
https://github.com/istio/glog/blob/d7cfb6fa2ccda15565f68f204d68907c80a5c977/glog.go#L58-L60
15,613
istio/glog
glog.go
Warningln
func Warningln(args ...interface{}) { s := fmt.Sprint(args) zap.S().Warn(s, "\n") }
go
func Warningln(args ...interface{}) { s := fmt.Sprint(args) zap.S().Warn(s, "\n") }
[ "func", "Warningln", "(", "args", "...", "interface", "{", "}", ")", "{", "s", ":=", "fmt", ".", "Sprint", "(", "args", ")", "\n", "zap", ".", "S", "(", ")", ".", "Warn", "(", "s", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// Warningln is a shim
[ "Warningln", "is", "a", "shim" ]
d7cfb6fa2ccda15565f68f204d68907c80a5c977
https://github.com/istio/glog/blob/d7cfb6fa2ccda15565f68f204d68907c80a5c977/glog.go#L94-L97
15,614
istio/glog
glog.go
Errorln
func Errorln(args ...interface{}) { s := fmt.Sprint(args) zap.S().Error(s, "\n") }
go
func Errorln(args ...interface{}) { s := fmt.Sprint(args) zap.S().Error(s, "\n") }
[ "func", "Errorln", "(", "args", "...", "interface", "{", "}", ")", "{", "s", ":=", "fmt", ".", "Sprint", "(", "args", ")", "\n", "zap", ".", "S", "(", ")", ".", "Error", "(", "s", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// Errorln is a shim
[ "Errorln", "is", "a", "shim" ]
d7cfb6fa2ccda15565f68f204d68907c80a5c977
https://github.com/istio/glog/blob/d7cfb6fa2ccda15565f68f204d68907c80a5c977/glog.go#L115-L118
15,615
istio/glog
glog.go
ExitDepth
func ExitDepth(depth int, args ...interface{}) { zap.S().Error(args...) os.Exit(1) }
go
func ExitDepth(depth int, args ...interface{}) { zap.S().Error(args...) os.Exit(1) }
[ "func", "ExitDepth", "(", "depth", "int", ",", "args", "...", "interface", "{", "}", ")", "{", "zap", ".", "S", "(", ")", ".", "Error", "(", "args", "...", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// ExitDepth is a shim
[ "ExitDepth", "is", "a", "shim" ]
d7cfb6fa2ccda15565f68f204d68907c80a5c977
https://github.com/istio/glog/blob/d7cfb6fa2ccda15565f68f204d68907c80a5c977/glog.go#L157-L160
15,616
istio/glog
glog.go
Exitln
func Exitln(args ...interface{}) { s := fmt.Sprint(args) zap.S().Error(s, "\n") os.Exit(1) }
go
func Exitln(args ...interface{}) { s := fmt.Sprint(args) zap.S().Error(s, "\n") os.Exit(1) }
[ "func", "Exitln", "(", "args", "...", "interface", "{", "}", ")", "{", "s", ":=", "fmt", ".", "Sprint", "(", "args", ")", "\n", "zap", ".", "S", "(", ")", ".", "Error", "(", "s", ",", "\"", "\\n", "\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// Exitln is a shim
[ "Exitln", "is", "a", "shim" ]
d7cfb6fa2ccda15565f68f204d68907c80a5c977
https://github.com/istio/glog/blob/d7cfb6fa2ccda15565f68f204d68907c80a5c977/glog.go#L163-L167
15,617
istio/glog
glog.go
Exitf
func Exitf(format string, args ...interface{}) { zap.S().Errorf(format, args...) os.Exit(1) }
go
func Exitf(format string, args ...interface{}) { zap.S().Errorf(format, args...) os.Exit(1) }
[ "func", "Exitf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "zap", ".", "S", "(", ")", ".", "Errorf", "(", "format", ",", "args", "...", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// Exitf is a shim
[ "Exitf", "is", "a", "shim" ]
d7cfb6fa2ccda15565f68f204d68907c80a5c977
https://github.com/istio/glog/blob/d7cfb6fa2ccda15565f68f204d68907c80a5c977/glog.go#L170-L173
15,618
volatiletech/abcweb
abcsessions/redis.go
All
func (r *RedisStorer) All() ([]string, error) { var sessions []string iter := r.client.Scan(0, "", 0).Iterator() for iter.Next() { sessions = append(sessions, iter.Val()) } err := iter.Err() return sessions, errors.Wrap(err, "unable to iterate redis store") }
go
func (r *RedisStorer) All() ([]string, error) { var sessions []string iter := r.client.Scan(0, "", 0).Iterator() for iter.Next() { sessions = append(sessions, iter.Val()) } err := iter.Err() return sessions, errors.Wrap(err, "unable to iterate redis store") }
[ "func", "(", "r", "*", "RedisStorer", ")", "All", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "sessions", "[", "]", "string", "\n\n", "iter", ":=", "r", ".", "client", ".", "Scan", "(", "0", ",", "\"", "\"", ",", "0", ")", ".", "Iterator", "(", ")", "\n", "for", "iter", ".", "Next", "(", ")", "{", "sessions", "=", "append", "(", "sessions", ",", "iter", ".", "Val", "(", ")", ")", "\n", "}", "\n", "err", ":=", "iter", ".", "Err", "(", ")", "\n", "return", "sessions", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// All keys in the redis store
[ "All", "keys", "in", "the", "redis", "store" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/redis.go#L51-L60
15,619
volatiletech/abcweb
abcsessions/cookie_overseer.go
NewCookieOverseer
func NewCookieOverseer(opts CookieOptions, secretKey []byte) *CookieOverseer { if len(opts.Name) == 0 { panic("cookie name must be provided") } block, err := aes.NewCipher(secretKey) if err != nil { panic(err) } gcm, err := cipher.NewGCM(block) if err != nil { panic(err) } o := &CookieOverseer{ options: opts, secretKey: secretKey, gcmBlockMode: gcm, } o.resetExpiryMiddleware.resetter = o return o }
go
func NewCookieOverseer(opts CookieOptions, secretKey []byte) *CookieOverseer { if len(opts.Name) == 0 { panic("cookie name must be provided") } block, err := aes.NewCipher(secretKey) if err != nil { panic(err) } gcm, err := cipher.NewGCM(block) if err != nil { panic(err) } o := &CookieOverseer{ options: opts, secretKey: secretKey, gcmBlockMode: gcm, } o.resetExpiryMiddleware.resetter = o return o }
[ "func", "NewCookieOverseer", "(", "opts", "CookieOptions", ",", "secretKey", "[", "]", "byte", ")", "*", "CookieOverseer", "{", "if", "len", "(", "opts", ".", "Name", ")", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "block", ",", "err", ":=", "aes", ".", "NewCipher", "(", "secretKey", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "gcm", ",", "err", ":=", "cipher", ".", "NewGCM", "(", "block", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "o", ":=", "&", "CookieOverseer", "{", "options", ":", "opts", ",", "secretKey", ":", "secretKey", ",", "gcmBlockMode", ":", "gcm", ",", "}", "\n\n", "o", ".", "resetExpiryMiddleware", ".", "resetter", "=", "o", "\n\n", "return", "o", "\n", "}" ]
// NewCookieOverseer creates an overseer from cookie options and a secret key // for use in encryption. Panic's on any errors that deal with cryptography.
[ "NewCookieOverseer", "creates", "an", "overseer", "from", "cookie", "options", "and", "a", "secret", "key", "for", "use", "in", "encryption", ".", "Panic", "s", "on", "any", "errors", "that", "deal", "with", "cryptography", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_overseer.go#L27-L50
15,620
volatiletech/abcweb
abcsessions/cookie_overseer.go
Get
func (c *CookieOverseer) Get(w http.ResponseWriter, r *http.Request) (string, error) { val, err := c.options.getCookieValue(w, r) if err != nil { return "", errors.Wrap(err, "unable to get session value from cookie") } return c.decode(val) }
go
func (c *CookieOverseer) Get(w http.ResponseWriter, r *http.Request) (string, error) { val, err := c.options.getCookieValue(w, r) if err != nil { return "", errors.Wrap(err, "unable to get session value from cookie") } return c.decode(val) }
[ "func", "(", "c", "*", "CookieOverseer", ")", "Get", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "val", ",", "err", ":=", "c", ".", "options", ".", "getCookieValue", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "c", ".", "decode", "(", "val", ")", "\n", "}" ]
// Get a value from the cookie overseer
[ "Get", "a", "value", "from", "the", "cookie", "overseer" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_overseer.go#L53-L60
15,621
volatiletech/abcweb
abcsessions/cookie_overseer.go
Set
func (c *CookieOverseer) Set(w http.ResponseWriter, r *http.Request, value string) error { ev, err := c.encode(value) if err != nil { return errors.Wrap(err, "unable to encode session value into cookie") } w.(cookieWriter).SetCookie(c.options.makeCookie(ev)) return nil }
go
func (c *CookieOverseer) Set(w http.ResponseWriter, r *http.Request, value string) error { ev, err := c.encode(value) if err != nil { return errors.Wrap(err, "unable to encode session value into cookie") } w.(cookieWriter).SetCookie(c.options.makeCookie(ev)) return nil }
[ "func", "(", "c", "*", "CookieOverseer", ")", "Set", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "value", "string", ")", "error", "{", "ev", ",", "err", ":=", "c", ".", "encode", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "w", ".", "(", "cookieWriter", ")", ".", "SetCookie", "(", "c", ".", "options", ".", "makeCookie", "(", "ev", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// Set a value into the cookie overseer
[ "Set", "a", "value", "into", "the", "cookie", "overseer" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_overseer.go#L63-L72
15,622
volatiletech/abcweb
abcsessions/cookie_overseer.go
Del
func (c *CookieOverseer) Del(w http.ResponseWriter, r *http.Request) error { c.options.deleteCookie(w) return nil }
go
func (c *CookieOverseer) Del(w http.ResponseWriter, r *http.Request) error { c.options.deleteCookie(w) return nil }
[ "func", "(", "c", "*", "CookieOverseer", ")", "Del", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "error", "{", "c", ".", "options", ".", "deleteCookie", "(", "w", ")", "\n", "return", "nil", "\n", "}" ]
// Del a value from the cookie overseer
[ "Del", "a", "value", "from", "the", "cookie", "overseer" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_overseer.go#L75-L78
15,623
volatiletech/abcweb
abcsessions/cookie_overseer.go
Regenerate
func (c *CookieOverseer) Regenerate(w http.ResponseWriter, r *http.Request) error { panic("cookie sessions do not use session ids") }
go
func (c *CookieOverseer) Regenerate(w http.ResponseWriter, r *http.Request) error { panic("cookie sessions do not use session ids") }
[ "func", "(", "c", "*", "CookieOverseer", ")", "Regenerate", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "error", "{", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// Regenerate for the cookie overseer will panic because cookie sessions // do not have session IDs, only values.
[ "Regenerate", "for", "the", "cookie", "overseer", "will", "panic", "because", "cookie", "sessions", "do", "not", "have", "session", "IDs", "only", "values", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_overseer.go#L82-L84
15,624
volatiletech/abcweb
abcsessions/cookie_overseer.go
SessionID
func (c *CookieOverseer) SessionID(w http.ResponseWriter, r *http.Request) (string, error) { panic("cookie sessions do not use session ids") }
go
func (c *CookieOverseer) SessionID(w http.ResponseWriter, r *http.Request) (string, error) { panic("cookie sessions do not use session ids") }
[ "func", "(", "c", "*", "CookieOverseer", ")", "SessionID", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// SessionID for the cookie overseer will panic because cookie sessions // do not have session IDs, only values.
[ "SessionID", "for", "the", "cookie", "overseer", "will", "panic", "because", "cookie", "sessions", "do", "not", "have", "session", "IDs", "only", "values", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_overseer.go#L88-L90
15,625
volatiletech/abcweb
abcsessions/cookie_overseer.go
encode
func (c *CookieOverseer) encode(plaintext string) (string, error) { nonce := make([]byte, c.gcmBlockMode.NonceSize()) if _, err := rand.Read(nonce); err != nil { return "", errors.Wrap(err, "failed to encode session cookie value") } // Append ciphertext to the end of nonce so we have the nonce for decrypt ciphertext := c.gcmBlockMode.Seal(nonce, nonce, []byte(plaintext), nil) return base64.StdEncoding.EncodeToString(ciphertext), nil }
go
func (c *CookieOverseer) encode(plaintext string) (string, error) { nonce := make([]byte, c.gcmBlockMode.NonceSize()) if _, err := rand.Read(nonce); err != nil { return "", errors.Wrap(err, "failed to encode session cookie value") } // Append ciphertext to the end of nonce so we have the nonce for decrypt ciphertext := c.gcmBlockMode.Seal(nonce, nonce, []byte(plaintext), nil) return base64.StdEncoding.EncodeToString(ciphertext), nil }
[ "func", "(", "c", "*", "CookieOverseer", ")", "encode", "(", "plaintext", "string", ")", "(", "string", ",", "error", ")", "{", "nonce", ":=", "make", "(", "[", "]", "byte", ",", "c", ".", "gcmBlockMode", ".", "NonceSize", "(", ")", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Read", "(", "nonce", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Append ciphertext to the end of nonce so we have the nonce for decrypt", "ciphertext", ":=", "c", ".", "gcmBlockMode", ".", "Seal", "(", "nonce", ",", "nonce", ",", "[", "]", "byte", "(", "plaintext", ")", ",", "nil", ")", "\n", "return", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "ciphertext", ")", ",", "nil", "\n", "}" ]
// encode into base64'd aes-gcm
[ "encode", "into", "base64", "d", "aes", "-", "gcm" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_overseer.go#L110-L119
15,626
volatiletech/abcweb
abcsessions/cookie_overseer.go
decode
func (c *CookieOverseer) decode(ciphertext string) (string, error) { ct, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { return "", nil } if len(ct) <= c.gcmBlockMode.NonceSize() { return "", errors.New("failed to decode session cookie value") } // Nonce comes from the first n bytes (n = NonceSize) plaintext, err := c.gcmBlockMode.Open(nil, ct[:c.gcmBlockMode.NonceSize()], ct[c.gcmBlockMode.NonceSize():], nil) if err != nil { return "", errors.Wrap(err, "unable to open gcm block mode") } return string(plaintext), nil }
go
func (c *CookieOverseer) decode(ciphertext string) (string, error) { ct, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { return "", nil } if len(ct) <= c.gcmBlockMode.NonceSize() { return "", errors.New("failed to decode session cookie value") } // Nonce comes from the first n bytes (n = NonceSize) plaintext, err := c.gcmBlockMode.Open(nil, ct[:c.gcmBlockMode.NonceSize()], ct[c.gcmBlockMode.NonceSize():], nil) if err != nil { return "", errors.Wrap(err, "unable to open gcm block mode") } return string(plaintext), nil }
[ "func", "(", "c", "*", "CookieOverseer", ")", "decode", "(", "ciphertext", "string", ")", "(", "string", ",", "error", ")", "{", "ct", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "ciphertext", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "if", "len", "(", "ct", ")", "<=", "c", ".", "gcmBlockMode", ".", "NonceSize", "(", ")", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Nonce comes from the first n bytes (n = NonceSize)", "plaintext", ",", "err", ":=", "c", ".", "gcmBlockMode", ".", "Open", "(", "nil", ",", "ct", "[", ":", "c", ".", "gcmBlockMode", ".", "NonceSize", "(", ")", "]", ",", "ct", "[", "c", ".", "gcmBlockMode", ".", "NonceSize", "(", ")", ":", "]", ",", "nil", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "string", "(", "plaintext", ")", ",", "nil", "\n", "}" ]
// decode base64'd aes-gcm
[ "decode", "base64", "d", "aes", "-", "gcm" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_overseer.go#L122-L143
15,627
volatiletech/abcweb
abcmiddleware/log.go
Zap
func (m Middleware) Zap(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { t := time.Now() zw := &zapResponseWriter{ResponseWriter: w} // Serve the request next.ServeHTTP(zw, r) // Write the request log line writeZap(m.Log, r, t, zw.status, zw.size) } return http.HandlerFunc(fn) }
go
func (m Middleware) Zap(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { t := time.Now() zw := &zapResponseWriter{ResponseWriter: w} // Serve the request next.ServeHTTP(zw, r) // Write the request log line writeZap(m.Log, r, t, zw.status, zw.size) } return http.HandlerFunc(fn) }
[ "func", "(", "m", "Middleware", ")", "Zap", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "fn", ":=", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "t", ":=", "time", ".", "Now", "(", ")", "\n", "zw", ":=", "&", "zapResponseWriter", "{", "ResponseWriter", ":", "w", "}", "\n\n", "// Serve the request", "next", ".", "ServeHTTP", "(", "zw", ",", "r", ")", "\n\n", "// Write the request log line", "writeZap", "(", "m", ".", "Log", ",", "r", ",", "t", ",", "zw", ".", "status", ",", "zw", ".", "size", ")", "\n", "}", "\n\n", "return", "http", ".", "HandlerFunc", "(", "fn", ")", "\n", "}" ]
// Zap middleware handles web request logging using Zap
[ "Zap", "middleware", "handles", "web", "request", "logging", "using", "Zap" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcmiddleware/log.go#L21-L34
15,628
volatiletech/abcweb
abcmiddleware/log.go
RequestIDLogger
func (m Middleware) RequestIDLogger(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { requestID := chimiddleware.GetReqID(r.Context()) derivedLogger := m.Log.With(zap.String("request_id", requestID)) r = r.WithContext(context.WithValue(r.Context(), CtxLoggerKey, derivedLogger)) next.ServeHTTP(w, r) } return http.HandlerFunc(fn) }
go
func (m Middleware) RequestIDLogger(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { requestID := chimiddleware.GetReqID(r.Context()) derivedLogger := m.Log.With(zap.String("request_id", requestID)) r = r.WithContext(context.WithValue(r.Context(), CtxLoggerKey, derivedLogger)) next.ServeHTTP(w, r) } return http.HandlerFunc(fn) }
[ "func", "(", "m", "Middleware", ")", "RequestIDLogger", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "fn", ":=", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "requestID", ":=", "chimiddleware", ".", "GetReqID", "(", "r", ".", "Context", "(", ")", ")", "\n", "derivedLogger", ":=", "m", ".", "Log", ".", "With", "(", "zap", ".", "String", "(", "\"", "\"", ",", "requestID", ")", ")", "\n", "r", "=", "r", ".", "WithContext", "(", "context", ".", "WithValue", "(", "r", ".", "Context", "(", ")", ",", "CtxLoggerKey", ",", "derivedLogger", ")", ")", "\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n\n", "return", "http", ".", "HandlerFunc", "(", "fn", ")", "\n", "}" ]
// RequestIDLogger middleware creates a derived logger to include logging of the // Request ID, and inserts it into the context object
[ "RequestIDLogger", "middleware", "creates", "a", "derived", "logger", "to", "include", "logging", "of", "the", "Request", "ID", "and", "inserts", "it", "into", "the", "context", "object" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcmiddleware/log.go#L38-L47
15,629
volatiletech/abcweb
abcmiddleware/log.go
Log
func Log(r *http.Request) *zap.Logger { v := r.Context().Value(CtxLoggerKey) log, ok := v.(*zap.Logger) if !ok { panic("cannot get derived request id logger from context object") } return log }
go
func Log(r *http.Request) *zap.Logger { v := r.Context().Value(CtxLoggerKey) log, ok := v.(*zap.Logger) if !ok { panic("cannot get derived request id logger from context object") } return log }
[ "func", "Log", "(", "r", "*", "http", ".", "Request", ")", "*", "zap", ".", "Logger", "{", "v", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "CtxLoggerKey", ")", "\n", "log", ",", "ok", ":=", "v", ".", "(", "*", "zap", ".", "Logger", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "log", "\n", "}" ]
// Log returns the Request ID scoped logger from the request Context // and panics if it cannot be found. This function is only ever used // by your controllers if your app uses the RequestID middlewares, // otherwise you should use the controller's receiver logger directly.
[ "Log", "returns", "the", "Request", "ID", "scoped", "logger", "from", "the", "request", "Context", "and", "panics", "if", "it", "cannot", "be", "found", ".", "This", "function", "is", "only", "ever", "used", "by", "your", "controllers", "if", "your", "app", "uses", "the", "RequestID", "middlewares", "otherwise", "you", "should", "use", "the", "controller", "s", "receiver", "logger", "directly", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcmiddleware/log.go#L53-L60
15,630
volatiletech/abcweb
abcmiddleware/recover.go
Recover
func (m Middleware) Recover(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { var protocol string if r.TLS == nil { protocol = "http" } else { protocol = "https" } var log *zap.Logger v := r.Context().Value(CtxLoggerKey) if v != nil { var ok bool log, ok = v.(*zap.Logger) if !ok { panic("cannot get derived request id logger from context object") } // log with the request_id scoped logger log.Error(fmt.Sprintf("%s request error", protocol), zap.String("method", r.Method), zap.String("uri", r.RequestURI), zap.Bool("tls", r.TLS != nil), zap.String("protocol", r.Proto), zap.String("host", r.Host), zap.String("remote_addr", r.RemoteAddr), zap.String("error", fmt.Sprintf("%+v", err)), ) } else { // log with the logger attached to middleware struct if // cannot find request_id scoped logger m.Log.Error(fmt.Sprintf("%s request error", protocol), zap.String("method", r.Method), zap.String("uri", r.RequestURI), zap.Bool("tls", r.TLS != nil), zap.String("protocol", r.Proto), zap.String("host", r.Host), zap.String("remote_addr", r.RemoteAddr), zap.String("error", fmt.Sprintf("%+v", err)), ) } // Return a http 500 with the HTTP body of "Internal Server Error" http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } }() next.ServeHTTP(w, r) } return http.HandlerFunc(fn) }
go
func (m Middleware) Recover(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { var protocol string if r.TLS == nil { protocol = "http" } else { protocol = "https" } var log *zap.Logger v := r.Context().Value(CtxLoggerKey) if v != nil { var ok bool log, ok = v.(*zap.Logger) if !ok { panic("cannot get derived request id logger from context object") } // log with the request_id scoped logger log.Error(fmt.Sprintf("%s request error", protocol), zap.String("method", r.Method), zap.String("uri", r.RequestURI), zap.Bool("tls", r.TLS != nil), zap.String("protocol", r.Proto), zap.String("host", r.Host), zap.String("remote_addr", r.RemoteAddr), zap.String("error", fmt.Sprintf("%+v", err)), ) } else { // log with the logger attached to middleware struct if // cannot find request_id scoped logger m.Log.Error(fmt.Sprintf("%s request error", protocol), zap.String("method", r.Method), zap.String("uri", r.RequestURI), zap.Bool("tls", r.TLS != nil), zap.String("protocol", r.Proto), zap.String("host", r.Host), zap.String("remote_addr", r.RemoteAddr), zap.String("error", fmt.Sprintf("%+v", err)), ) } // Return a http 500 with the HTTP body of "Internal Server Error" http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } }() next.ServeHTTP(w, r) } return http.HandlerFunc(fn) }
[ "func", "(", "m", "Middleware", ")", "Recover", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "fn", ":=", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "defer", "func", "(", ")", "{", "if", "err", ":=", "recover", "(", ")", ";", "err", "!=", "nil", "{", "var", "protocol", "string", "\n", "if", "r", ".", "TLS", "==", "nil", "{", "protocol", "=", "\"", "\"", "\n", "}", "else", "{", "protocol", "=", "\"", "\"", "\n", "}", "\n\n", "var", "log", "*", "zap", ".", "Logger", "\n", "v", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "CtxLoggerKey", ")", "\n", "if", "v", "!=", "nil", "{", "var", "ok", "bool", "\n", "log", ",", "ok", "=", "v", ".", "(", "*", "zap", ".", "Logger", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// log with the request_id scoped logger", "log", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "protocol", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Method", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "RequestURI", ")", ",", "zap", ".", "Bool", "(", "\"", "\"", ",", "r", ".", "TLS", "!=", "nil", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Proto", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Host", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "RemoteAddr", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", ",", ")", "\n", "}", "else", "{", "// log with the logger attached to middleware struct if", "// cannot find request_id scoped logger", "m", ".", "Log", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "protocol", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Method", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "RequestURI", ")", ",", "zap", ".", "Bool", "(", "\"", "\"", ",", "r", ".", "TLS", "!=", "nil", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Proto", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Host", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "RemoteAddr", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", ",", ")", "\n", "}", "\n\n", "// Return a http 500 with the HTTP body of \"Internal Server Error\"", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "http", ".", "StatusInternalServerError", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "\n\n", "return", "http", ".", "HandlerFunc", "(", "fn", ")", "\n", "}" ]
// Recover middleware recovers panics that occur and gracefully logs their error
[ "Recover", "middleware", "recovers", "panics", "that", "occur", "and", "gracefully", "logs", "their", "error" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcmiddleware/recover.go#L11-L63
15,631
volatiletech/abcweb
cert/cert.go
Template
func Template(appName, commonName string) (*x509.Certificate, error) { // generate a random serial number (a real cert authority would have some logic behind this) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, errors.New("failed to generate serial number: " + err.Error()) } tmpl := x509.Certificate{ IsCA: true, SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{appName}, CommonName: commonName, }, SignatureAlgorithm: x509.SHA256WithRSA, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour * 24 * 365 * 4), // valid for 4 years BasicConstraintsValid: true, } return &tmpl, nil }
go
func Template(appName, commonName string) (*x509.Certificate, error) { // generate a random serial number (a real cert authority would have some logic behind this) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, errors.New("failed to generate serial number: " + err.Error()) } tmpl := x509.Certificate{ IsCA: true, SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{appName}, CommonName: commonName, }, SignatureAlgorithm: x509.SHA256WithRSA, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour * 24 * 365 * 4), // valid for 4 years BasicConstraintsValid: true, } return &tmpl, nil }
[ "func", "Template", "(", "appName", ",", "commonName", "string", ")", "(", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "// generate a random serial number (a real cert authority would have some logic behind this)", "serialNumberLimit", ":=", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "big", ".", "NewInt", "(", "1", ")", ",", "128", ")", "\n", "serialNumber", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", "Reader", ",", "serialNumberLimit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "tmpl", ":=", "x509", ".", "Certificate", "{", "IsCA", ":", "true", ",", "SerialNumber", ":", "serialNumber", ",", "Subject", ":", "pkix", ".", "Name", "{", "Organization", ":", "[", "]", "string", "{", "appName", "}", ",", "CommonName", ":", "commonName", ",", "}", ",", "SignatureAlgorithm", ":", "x509", ".", "SHA256WithRSA", ",", "NotBefore", ":", "time", ".", "Now", "(", ")", ",", "NotAfter", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Hour", "*", "24", "*", "365", "*", "4", ")", ",", "// valid for 4 years", "BasicConstraintsValid", ":", "true", ",", "}", "\n\n", "return", "&", "tmpl", ",", "nil", "\n", "}" ]
// Template is a helper function to create a cert template with a // serial number and other required fields
[ "Template", "is", "a", "helper", "function", "to", "create", "a", "cert", "template", "with", "a", "serial", "number", "and", "other", "required", "fields" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/cert/cert.go#L18-L41
15,632
volatiletech/abcweb
cert/cert.go
WriteCertFile
func WriteCertFile(outFile afero.File, template *x509.Certificate, pub interface{}, priv interface{}) error { certDER, err := x509.CreateCertificate(rand.Reader, template, template, pub, priv) if err != nil { return err } // PEM encode the certificate (this is a standard TLS encoding) b := &pem.Block{ Type: "CERTIFICATE", Bytes: certDER, } return pem.Encode(outFile, b) }
go
func WriteCertFile(outFile afero.File, template *x509.Certificate, pub interface{}, priv interface{}) error { certDER, err := x509.CreateCertificate(rand.Reader, template, template, pub, priv) if err != nil { return err } // PEM encode the certificate (this is a standard TLS encoding) b := &pem.Block{ Type: "CERTIFICATE", Bytes: certDER, } return pem.Encode(outFile, b) }
[ "func", "WriteCertFile", "(", "outFile", "afero", ".", "File", ",", "template", "*", "x509", ".", "Certificate", ",", "pub", "interface", "{", "}", ",", "priv", "interface", "{", "}", ")", "error", "{", "certDER", ",", "err", ":=", "x509", ".", "CreateCertificate", "(", "rand", ".", "Reader", ",", "template", ",", "template", ",", "pub", ",", "priv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// PEM encode the certificate (this is a standard TLS encoding)", "b", ":=", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "certDER", ",", "}", "\n\n", "return", "pem", ".", "Encode", "(", "outFile", ",", "b", ")", "\n", "}" ]
// WriteCertFile writes the cert.pem certificate file
[ "WriteCertFile", "writes", "the", "cert", ".", "pem", "certificate", "file" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/cert/cert.go#L44-L57
15,633
volatiletech/abcweb
cert/cert.go
WritePrivateKey
func WritePrivateKey(outFile afero.File, key *rsa.PrivateKey) error { b := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), } return pem.Encode(outFile, b) }
go
func WritePrivateKey(outFile afero.File, key *rsa.PrivateKey) error { b := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key), } return pem.Encode(outFile, b) }
[ "func", "WritePrivateKey", "(", "outFile", "afero", ".", "File", ",", "key", "*", "rsa", ".", "PrivateKey", ")", "error", "{", "b", ":=", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "x509", ".", "MarshalPKCS1PrivateKey", "(", "key", ")", ",", "}", "\n\n", "return", "pem", ".", "Encode", "(", "outFile", ",", "b", ")", "\n", "}" ]
// WritePrivateKey writes the private.key private key file
[ "WritePrivateKey", "writes", "the", "private", ".", "key", "private", "key", "file" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/cert/cert.go#L60-L67
15,634
volatiletech/abcweb
abcserver/routes.go
NewNotFoundHandler
func NewNotFoundHandler(manifest map[string]string) *NotFound { return &NotFound{ Templates: NotFoundTemplates{ NotFound: "errors/404", InternalServerError: "errors/500", }, AssetsManifest: manifest, } }
go
func NewNotFoundHandler(manifest map[string]string) *NotFound { return &NotFound{ Templates: NotFoundTemplates{ NotFound: "errors/404", InternalServerError: "errors/500", }, AssetsManifest: manifest, } }
[ "func", "NewNotFoundHandler", "(", "manifest", "map", "[", "string", "]", "string", ")", "*", "NotFound", "{", "return", "&", "NotFound", "{", "Templates", ":", "NotFoundTemplates", "{", "NotFound", ":", "\"", "\"", ",", "InternalServerError", ":", "\"", "\"", ",", "}", ",", "AssetsManifest", ":", "manifest", ",", "}", "\n", "}" ]
// NewNotFoundHandler creates a new handler
[ "NewNotFoundHandler", "creates", "a", "new", "handler" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcserver/routes.go#L49-L57
15,635
volatiletech/abcweb
abcserver/routes.go
Handler
func (m *MethodNotAllowed) Handler(render abcrender.Renderer) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Get the Request ID scoped logger log := abcmiddleware.Log(r) log.Warn("method not allowed", zap.String("method", r.Method), zap.String("uri", r.RequestURI), zap.Bool("tls", r.TLS != nil), zap.String("protocol", r.Proto), zap.String("host", r.Host), zap.String("remote_addr", r.RemoteAddr), ) if err := render.HTML(w, http.StatusMethodNotAllowed, m.Templates.MethodNotAllowed, nil); err != nil { panic(err) } } }
go
func (m *MethodNotAllowed) Handler(render abcrender.Renderer) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Get the Request ID scoped logger log := abcmiddleware.Log(r) log.Warn("method not allowed", zap.String("method", r.Method), zap.String("uri", r.RequestURI), zap.Bool("tls", r.TLS != nil), zap.String("protocol", r.Proto), zap.String("host", r.Host), zap.String("remote_addr", r.RemoteAddr), ) if err := render.HTML(w, http.StatusMethodNotAllowed, m.Templates.MethodNotAllowed, nil); err != nil { panic(err) } } }
[ "func", "(", "m", "*", "MethodNotAllowed", ")", "Handler", "(", "render", "abcrender", ".", "Renderer", ")", "http", ".", "HandlerFunc", "{", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Get the Request ID scoped logger", "log", ":=", "abcmiddleware", ".", "Log", "(", "r", ")", "\n\n", "log", ".", "Warn", "(", "\"", "\"", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Method", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "RequestURI", ")", ",", "zap", ".", "Bool", "(", "\"", "\"", ",", "r", ".", "TLS", "!=", "nil", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Proto", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Host", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "RemoteAddr", ")", ",", ")", "\n\n", "if", "err", ":=", "render", ".", "HTML", "(", "w", ",", "http", ".", "StatusMethodNotAllowed", ",", "m", ".", "Templates", ".", "MethodNotAllowed", ",", "nil", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Handler is a wrapper around the MethodNotAllowed handler. // The MethodNotAllowed handler is called when someone attempts an operation // against a route that does not support that operation, for example // attempting a POST against a route that only supports a GET.
[ "Handler", "is", "a", "wrapper", "around", "the", "MethodNotAllowed", "handler", ".", "The", "MethodNotAllowed", "handler", "is", "called", "when", "someone", "attempts", "an", "operation", "against", "a", "route", "that", "does", "not", "support", "that", "operation", "for", "example", "attempting", "a", "POST", "against", "a", "route", "that", "only", "supports", "a", "GET", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcserver/routes.go#L168-L186
15,636
volatiletech/abcweb
abcconfig/config.go
Bind
func (c *Config) Bind(flags *pflag.FlagSet, cfg interface{}) (*viper.Viper, error) { v, err := c.NewSubViper(flags, cfg) if err != nil { return v, err } if err := UnmarshalAppConfig(cfg, v); err != nil { return v, err } val := reflect.Indirect(reflect.ValueOf(cfg)) // Check if there's a DBConfig object in the cfg struct. // If found, then validate all fields on it are set appropriately. for i := 0; i < val.NumField(); i++ { dbCfg, ok := val.Field(i).Interface().(DBConfig) if !ok { continue } if err := ValidateDBConfig(dbCfg); err != nil { return v, err } break } return v, nil }
go
func (c *Config) Bind(flags *pflag.FlagSet, cfg interface{}) (*viper.Viper, error) { v, err := c.NewSubViper(flags, cfg) if err != nil { return v, err } if err := UnmarshalAppConfig(cfg, v); err != nil { return v, err } val := reflect.Indirect(reflect.ValueOf(cfg)) // Check if there's a DBConfig object in the cfg struct. // If found, then validate all fields on it are set appropriately. for i := 0; i < val.NumField(); i++ { dbCfg, ok := val.Field(i).Interface().(DBConfig) if !ok { continue } if err := ValidateDBConfig(dbCfg); err != nil { return v, err } break } return v, nil }
[ "func", "(", "c", "*", "Config", ")", "Bind", "(", "flags", "*", "pflag", ".", "FlagSet", ",", "cfg", "interface", "{", "}", ")", "(", "*", "viper", ".", "Viper", ",", "error", ")", "{", "v", ",", "err", ":=", "c", ".", "NewSubViper", "(", "flags", ",", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "UnmarshalAppConfig", "(", "cfg", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n\n", "val", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "cfg", ")", ")", "\n\n", "// Check if there's a DBConfig object in the cfg struct.", "// If found, then validate all fields on it are set appropriately.", "for", "i", ":=", "0", ";", "i", "<", "val", ".", "NumField", "(", ")", ";", "i", "++", "{", "dbCfg", ",", "ok", ":=", "val", ".", "Field", "(", "i", ")", ".", "Interface", "(", ")", ".", "(", "DBConfig", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "if", "err", ":=", "ValidateDBConfig", "(", "dbCfg", ")", ";", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "break", "\n", "}", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// Bind your passed in config flags to a new viper // instance, retrieves the active environment section of your config file using // that viper instance, and then loads your server and db config into // the passed in cfg struct and validates the db config is set appropriately.
[ "Bind", "your", "passed", "in", "config", "flags", "to", "a", "new", "viper", "instance", "retrieves", "the", "active", "environment", "section", "of", "your", "config", "file", "using", "that", "viper", "instance", "and", "then", "loads", "your", "server", "and", "db", "config", "into", "the", "passed", "in", "cfg", "struct", "and", "validates", "the", "db", "config", "is", "set", "appropriately", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcconfig/config.go#L116-L142
15,637
volatiletech/abcweb
abcconfig/config.go
NewSubViper
func (c *Config) NewSubViper(flags *pflag.FlagSet, cfg interface{}) (*viper.Viper, error) { v := viper.New() if flags != nil { if err := v.BindPFlags(flags); err != nil { return nil, err } } if err := c.ConfigureViper(v); err != nil { return nil, err } // Use the env from the config if it's not explicitly set env := c.LoadEnv if env == "" { env = v.GetString("env") } v = v.Sub(env) if v == nil { return nil, fmt.Errorf("cannot find env section named %s", env) } mappings, err := GetTagMappings(cfg) if err != nil { return nil, errors.Wrap(err, "unable to get tag mappings for config struct") } if c.EnvPrefix != "" { for _, m := range mappings { v.BindEnv(m.chain, strings.Join([]string{c.EnvPrefix, m.env}, "_")) } } else { for _, m := range mappings { v.BindEnv(m.chain, m.env) } } if v == nil { return nil, fmt.Errorf("unable to load environment %q from %q", env, c.File) } if flags != nil { if err := v.BindPFlags(flags); err != nil { return nil, err } } v.Set("env", env) return v, nil }
go
func (c *Config) NewSubViper(flags *pflag.FlagSet, cfg interface{}) (*viper.Viper, error) { v := viper.New() if flags != nil { if err := v.BindPFlags(flags); err != nil { return nil, err } } if err := c.ConfigureViper(v); err != nil { return nil, err } // Use the env from the config if it's not explicitly set env := c.LoadEnv if env == "" { env = v.GetString("env") } v = v.Sub(env) if v == nil { return nil, fmt.Errorf("cannot find env section named %s", env) } mappings, err := GetTagMappings(cfg) if err != nil { return nil, errors.Wrap(err, "unable to get tag mappings for config struct") } if c.EnvPrefix != "" { for _, m := range mappings { v.BindEnv(m.chain, strings.Join([]string{c.EnvPrefix, m.env}, "_")) } } else { for _, m := range mappings { v.BindEnv(m.chain, m.env) } } if v == nil { return nil, fmt.Errorf("unable to load environment %q from %q", env, c.File) } if flags != nil { if err := v.BindPFlags(flags); err != nil { return nil, err } } v.Set("env", env) return v, nil }
[ "func", "(", "c", "*", "Config", ")", "NewSubViper", "(", "flags", "*", "pflag", ".", "FlagSet", ",", "cfg", "interface", "{", "}", ")", "(", "*", "viper", ".", "Viper", ",", "error", ")", "{", "v", ":=", "viper", ".", "New", "(", ")", "\n\n", "if", "flags", "!=", "nil", "{", "if", "err", ":=", "v", ".", "BindPFlags", "(", "flags", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "ConfigureViper", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Use the env from the config if it's not explicitly set", "env", ":=", "c", ".", "LoadEnv", "\n", "if", "env", "==", "\"", "\"", "{", "env", "=", "v", ".", "GetString", "(", "\"", "\"", ")", "\n", "}", "\n\n", "v", "=", "v", ".", "Sub", "(", "env", ")", "\n", "if", "v", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "env", ")", "\n", "}", "\n\n", "mappings", ",", "err", ":=", "GetTagMappings", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "c", ".", "EnvPrefix", "!=", "\"", "\"", "{", "for", "_", ",", "m", ":=", "range", "mappings", "{", "v", ".", "BindEnv", "(", "m", ".", "chain", ",", "strings", ".", "Join", "(", "[", "]", "string", "{", "c", ".", "EnvPrefix", ",", "m", ".", "env", "}", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "else", "{", "for", "_", ",", "m", ":=", "range", "mappings", "{", "v", ".", "BindEnv", "(", "m", ".", "chain", ",", "m", ".", "env", ")", "\n", "}", "\n", "}", "\n\n", "if", "v", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "env", ",", "c", ".", "File", ")", "\n", "}", "\n\n", "if", "flags", "!=", "nil", "{", "if", "err", ":=", "v", ".", "BindPFlags", "(", "flags", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "v", ".", "Set", "(", "\"", "\"", ",", "env", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// NewSubViper returns a viper instance activated against the active environment // configuration subsection and initialized with the config.toml // configuration file and the environment variable prefix. // It also takes in the configuration struct so that it can generate the env // mappings.
[ "NewSubViper", "returns", "a", "viper", "instance", "activated", "against", "the", "active", "environment", "configuration", "subsection", "and", "initialized", "with", "the", "config", ".", "toml", "configuration", "file", "and", "the", "environment", "variable", "prefix", ".", "It", "also", "takes", "in", "the", "configuration", "struct", "so", "that", "it", "can", "generate", "the", "env", "mappings", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcconfig/config.go#L149-L200
15,638
volatiletech/abcweb
abcconfig/config.go
ConfigureViper
func (c *Config) ConfigureViper(v *viper.Viper) error { v.SetConfigType("toml") v.SetConfigFile(c.File) v.SetEnvPrefix(c.EnvPrefix) v.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) if err := v.ReadInConfig(); err != nil { return err } v.AutomaticEnv() return nil }
go
func (c *Config) ConfigureViper(v *viper.Viper) error { v.SetConfigType("toml") v.SetConfigFile(c.File) v.SetEnvPrefix(c.EnvPrefix) v.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) if err := v.ReadInConfig(); err != nil { return err } v.AutomaticEnv() return nil }
[ "func", "(", "c", "*", "Config", ")", "ConfigureViper", "(", "v", "*", "viper", ".", "Viper", ")", "error", "{", "v", ".", "SetConfigType", "(", "\"", "\"", ")", "\n", "v", ".", "SetConfigFile", "(", "c", ".", "File", ")", "\n", "v", ".", "SetEnvPrefix", "(", "c", ".", "EnvPrefix", ")", "\n", "v", ".", "SetEnvKeyReplacer", "(", "strings", ".", "NewReplacer", "(", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "if", "err", ":=", "v", ".", "ReadInConfig", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "v", ".", "AutomaticEnv", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// ConfigureViper sets the viper object to use the passed in config toml file // and also configures the configuration environment variables.
[ "ConfigureViper", "sets", "the", "viper", "object", "to", "use", "the", "passed", "in", "config", "toml", "file", "and", "also", "configures", "the", "configuration", "environment", "variables", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcconfig/config.go#L204-L215
15,639
volatiletech/abcweb
abcconfig/config.go
UnmarshalAppConfig
func UnmarshalAppConfig(cfg interface{}, v *viper.Viper) error { err := v.Unmarshal(cfg) if err != nil { return err } val := reflect.Indirect(reflect.ValueOf(cfg)) // if cfg has an imbedded AppConfig then we need to unmarshal // directly into that and overwrite it in the parent struct, // since its another layer of indirection and viper // can't handle it magically. for i := 0; i < val.NumField(); i++ { appCfg, ok := val.Field(i).Interface().(AppConfig) if !ok { continue } v.Unmarshal(&appCfg) val.Field(i).Set(reflect.ValueOf(appCfg)) // overwrite val to point to the AppConfig so DBConfig can be set below. val = val.Field(i) break } // Find *DBConfig and set object appropriately for i := 0; i < val.NumField(); i++ { dbCfg, ok := val.Field(i).Interface().(DBConfig) if !ok { continue } if dbCfg.DB == "postgres" { if dbCfg.Port == 0 { dbCfg.Port = 5432 } if dbCfg.SSLMode == "" { dbCfg.SSLMode = "require" } } else if dbCfg.DB == "mysql" { if dbCfg.Port == 0 { dbCfg.Port = 3306 } if dbCfg.SSLMode == "" { dbCfg.SSLMode = "true" } } val.Field(i).Set(reflect.ValueOf(dbCfg)) // Finished working on the db cfg struct, so break out break } return nil }
go
func UnmarshalAppConfig(cfg interface{}, v *viper.Viper) error { err := v.Unmarshal(cfg) if err != nil { return err } val := reflect.Indirect(reflect.ValueOf(cfg)) // if cfg has an imbedded AppConfig then we need to unmarshal // directly into that and overwrite it in the parent struct, // since its another layer of indirection and viper // can't handle it magically. for i := 0; i < val.NumField(); i++ { appCfg, ok := val.Field(i).Interface().(AppConfig) if !ok { continue } v.Unmarshal(&appCfg) val.Field(i).Set(reflect.ValueOf(appCfg)) // overwrite val to point to the AppConfig so DBConfig can be set below. val = val.Field(i) break } // Find *DBConfig and set object appropriately for i := 0; i < val.NumField(); i++ { dbCfg, ok := val.Field(i).Interface().(DBConfig) if !ok { continue } if dbCfg.DB == "postgres" { if dbCfg.Port == 0 { dbCfg.Port = 5432 } if dbCfg.SSLMode == "" { dbCfg.SSLMode = "require" } } else if dbCfg.DB == "mysql" { if dbCfg.Port == 0 { dbCfg.Port = 3306 } if dbCfg.SSLMode == "" { dbCfg.SSLMode = "true" } } val.Field(i).Set(reflect.ValueOf(dbCfg)) // Finished working on the db cfg struct, so break out break } return nil }
[ "func", "UnmarshalAppConfig", "(", "cfg", "interface", "{", "}", ",", "v", "*", "viper", ".", "Viper", ")", "error", "{", "err", ":=", "v", ".", "Unmarshal", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "val", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "cfg", ")", ")", "\n\n", "// if cfg has an imbedded AppConfig then we need to unmarshal", "// directly into that and overwrite it in the parent struct,", "// since its another layer of indirection and viper", "// can't handle it magically.", "for", "i", ":=", "0", ";", "i", "<", "val", ".", "NumField", "(", ")", ";", "i", "++", "{", "appCfg", ",", "ok", ":=", "val", ".", "Field", "(", "i", ")", ".", "Interface", "(", ")", ".", "(", "AppConfig", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "v", ".", "Unmarshal", "(", "&", "appCfg", ")", "\n", "val", ".", "Field", "(", "i", ")", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "appCfg", ")", ")", "\n", "// overwrite val to point to the AppConfig so DBConfig can be set below.", "val", "=", "val", ".", "Field", "(", "i", ")", "\n", "break", "\n", "}", "\n\n", "// Find *DBConfig and set object appropriately", "for", "i", ":=", "0", ";", "i", "<", "val", ".", "NumField", "(", ")", ";", "i", "++", "{", "dbCfg", ",", "ok", ":=", "val", ".", "Field", "(", "i", ")", ".", "Interface", "(", ")", ".", "(", "DBConfig", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "if", "dbCfg", ".", "DB", "==", "\"", "\"", "{", "if", "dbCfg", ".", "Port", "==", "0", "{", "dbCfg", ".", "Port", "=", "5432", "\n", "}", "\n", "if", "dbCfg", ".", "SSLMode", "==", "\"", "\"", "{", "dbCfg", ".", "SSLMode", "=", "\"", "\"", "\n", "}", "\n", "}", "else", "if", "dbCfg", ".", "DB", "==", "\"", "\"", "{", "if", "dbCfg", ".", "Port", "==", "0", "{", "dbCfg", ".", "Port", "=", "3306", "\n", "}", "\n", "if", "dbCfg", ".", "SSLMode", "==", "\"", "\"", "{", "dbCfg", ".", "SSLMode", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "val", ".", "Field", "(", "i", ")", ".", "Set", "(", "reflect", ".", "ValueOf", "(", "dbCfg", ")", ")", "\n\n", "// Finished working on the db cfg struct, so break out", "break", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalAppConfig unmarshals the viper's configured config file // into the passed in cfg object containing an AppConfig
[ "UnmarshalAppConfig", "unmarshals", "the", "viper", "s", "configured", "config", "file", "into", "the", "passed", "in", "cfg", "object", "containing", "an", "AppConfig" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcconfig/config.go#L219-L274
15,640
volatiletech/abcweb
abcconfig/config.go
ValidateDBConfig
func ValidateDBConfig(cfg DBConfig) error { err := vala.BeginValidation().Validate( vala.StringNotEmpty(cfg.DB, "db"), vala.StringNotEmpty(cfg.User, "user"), vala.StringNotEmpty(cfg.Host, "host"), vala.Not(vala.Equals(cfg.Port, 0, "port")), vala.StringNotEmpty(cfg.DBName, "dbname"), vala.StringNotEmpty(cfg.SSLMode, "sslmode"), ).Check() if err != nil { return err } if cfg.DB != "postgres" && cfg.DB != "mysql" { return errors.New("not a valid driver name") } return nil }
go
func ValidateDBConfig(cfg DBConfig) error { err := vala.BeginValidation().Validate( vala.StringNotEmpty(cfg.DB, "db"), vala.StringNotEmpty(cfg.User, "user"), vala.StringNotEmpty(cfg.Host, "host"), vala.Not(vala.Equals(cfg.Port, 0, "port")), vala.StringNotEmpty(cfg.DBName, "dbname"), vala.StringNotEmpty(cfg.SSLMode, "sslmode"), ).Check() if err != nil { return err } if cfg.DB != "postgres" && cfg.DB != "mysql" { return errors.New("not a valid driver name") } return nil }
[ "func", "ValidateDBConfig", "(", "cfg", "DBConfig", ")", "error", "{", "err", ":=", "vala", ".", "BeginValidation", "(", ")", ".", "Validate", "(", "vala", ".", "StringNotEmpty", "(", "cfg", ".", "DB", ",", "\"", "\"", ")", ",", "vala", ".", "StringNotEmpty", "(", "cfg", ".", "User", ",", "\"", "\"", ")", ",", "vala", ".", "StringNotEmpty", "(", "cfg", ".", "Host", ",", "\"", "\"", ")", ",", "vala", ".", "Not", "(", "vala", ".", "Equals", "(", "cfg", ".", "Port", ",", "0", ",", "\"", "\"", ")", ")", ",", "vala", ".", "StringNotEmpty", "(", "cfg", ".", "DBName", ",", "\"", "\"", ")", ",", "vala", ".", "StringNotEmpty", "(", "cfg", ".", "SSLMode", ",", "\"", "\"", ")", ",", ")", ".", "Check", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "cfg", ".", "DB", "!=", "\"", "\"", "&&", "cfg", ".", "DB", "!=", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ValidateDBConfig returns an error if any of the required db config // fields are not set to their appropriate values.
[ "ValidateDBConfig", "returns", "an", "error", "if", "any", "of", "the", "required", "db", "config", "fields", "are", "not", "set", "to", "their", "appropriate", "values", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcconfig/config.go#L278-L296
15,641
volatiletech/abcweb
abcconfig/config.go
GetTagMappings
func GetTagMappings(cfg interface{}) (Mappings, error) { return getTagMappingsRecursive("", reflect.Indirect(reflect.ValueOf(cfg))) }
go
func GetTagMappings(cfg interface{}) (Mappings, error) { return getTagMappingsRecursive("", reflect.Indirect(reflect.ValueOf(cfg))) }
[ "func", "GetTagMappings", "(", "cfg", "interface", "{", "}", ")", "(", "Mappings", ",", "error", ")", "{", "return", "getTagMappingsRecursive", "(", "\"", "\"", ",", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "cfg", ")", ")", ")", "\n", "}" ]
// GetTagMappings returns the viper .BindEnv mappings for an entire config // struct.
[ "GetTagMappings", "returns", "the", "viper", ".", "BindEnv", "mappings", "for", "an", "entire", "config", "struct", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcconfig/config.go#L363-L365
15,642
volatiletech/abcweb
abcdatabase/database.go
GetConnStr
func GetConnStr(cfg abcconfig.DBConfig) (string, error) { if len(cfg.DB) == 0 { return "", errors.New("db field in config.toml must be provided") } if cfg.DB == "postgres" { return drivers.PostgresBuildQueryString(cfg.User, cfg.Pass, cfg.DBName, cfg.Host, cfg.Port, cfg.SSLMode), nil } else if cfg.DB == "mysql" { return drivers.MySQLBuildQueryString(cfg.User, cfg.Pass, cfg.DBName, cfg.Host, cfg.Port, cfg.SSLMode), nil } return "", fmt.Errorf("cannot get connection string for unknown database %q", cfg.DB) }
go
func GetConnStr(cfg abcconfig.DBConfig) (string, error) { if len(cfg.DB) == 0 { return "", errors.New("db field in config.toml must be provided") } if cfg.DB == "postgres" { return drivers.PostgresBuildQueryString(cfg.User, cfg.Pass, cfg.DBName, cfg.Host, cfg.Port, cfg.SSLMode), nil } else if cfg.DB == "mysql" { return drivers.MySQLBuildQueryString(cfg.User, cfg.Pass, cfg.DBName, cfg.Host, cfg.Port, cfg.SSLMode), nil } return "", fmt.Errorf("cannot get connection string for unknown database %q", cfg.DB) }
[ "func", "GetConnStr", "(", "cfg", "abcconfig", ".", "DBConfig", ")", "(", "string", ",", "error", ")", "{", "if", "len", "(", "cfg", ".", "DB", ")", "==", "0", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cfg", ".", "DB", "==", "\"", "\"", "{", "return", "drivers", ".", "PostgresBuildQueryString", "(", "cfg", ".", "User", ",", "cfg", ".", "Pass", ",", "cfg", ".", "DBName", ",", "cfg", ".", "Host", ",", "cfg", ".", "Port", ",", "cfg", ".", "SSLMode", ")", ",", "nil", "\n", "}", "else", "if", "cfg", ".", "DB", "==", "\"", "\"", "{", "return", "drivers", ".", "MySQLBuildQueryString", "(", "cfg", ".", "User", ",", "cfg", ".", "Pass", ",", "cfg", ".", "DBName", ",", "cfg", ".", "Host", ",", "cfg", ".", "Port", ",", "cfg", ".", "SSLMode", ")", ",", "nil", "\n", "}", "\n\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cfg", ".", "DB", ")", "\n", "}" ]
// GetConnStr returns a connection string for the database software used
[ "GetConnStr", "returns", "a", "connection", "string", "for", "the", "database", "software", "used" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcdatabase/database.go#L34-L46
15,643
volatiletech/abcweb
abcdatabase/database.go
SetupDBData
func SetupDBData(cfg abcconfig.DBConfig, testdata TestdataFunc) (int, error) { var err error appPath := git.GetAppPath() err = createTestDB(cfg) if err != nil { return 0, err } count, err := RunMigrations(cfg, filepath.Join(appPath, "db", "migrations")) if err != nil { return count, errors.Wrap(err, "cannot execute migrations up") } testdataFile := filepath.Join(appPath, "db", "testdata.sql") err = SetupTestdata(cfg, testdataFile, testdata) return count, err }
go
func SetupDBData(cfg abcconfig.DBConfig, testdata TestdataFunc) (int, error) { var err error appPath := git.GetAppPath() err = createTestDB(cfg) if err != nil { return 0, err } count, err := RunMigrations(cfg, filepath.Join(appPath, "db", "migrations")) if err != nil { return count, errors.Wrap(err, "cannot execute migrations up") } testdataFile := filepath.Join(appPath, "db", "testdata.sql") err = SetupTestdata(cfg, testdataFile, testdata) return count, err }
[ "func", "SetupDBData", "(", "cfg", "abcconfig", ".", "DBConfig", ",", "testdata", "TestdataFunc", ")", "(", "int", ",", "error", ")", "{", "var", "err", "error", "\n\n", "appPath", ":=", "git", ".", "GetAppPath", "(", ")", "\n\n", "err", "=", "createTestDB", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "count", ",", "err", ":=", "RunMigrations", "(", "cfg", ",", "filepath", ".", "Join", "(", "appPath", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "count", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "testdataFile", ":=", "filepath", ".", "Join", "(", "appPath", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "err", "=", "SetupTestdata", "(", "cfg", ",", "testdataFile", ",", "testdata", ")", "\n\n", "return", "count", ",", "err", "\n", "}" ]
// SetupDBData executes the migrations "up" against the passed in database // and also inserts the test data defined in testdata.sql and executes // the passed in TestdataFunc handler if present, and then returns the // number of migrations run.
[ "SetupDBData", "executes", "the", "migrations", "up", "against", "the", "passed", "in", "database", "and", "also", "inserts", "the", "test", "data", "defined", "in", "testdata", ".", "sql", "and", "executes", "the", "passed", "in", "TestdataFunc", "handler", "if", "present", "and", "then", "returns", "the", "number", "of", "migrations", "run", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcdatabase/database.go#L127-L146
15,644
volatiletech/abcweb
abcdatabase/database.go
RunMigrations
func RunMigrations(cfg abcconfig.DBConfig, migrationsPath string) (int, error) { connStr, err := GetConnStr(cfg) if err != nil { return 0, err } count, err := mig.Up(cfg.DB, connStr, migrationsPath) if err != nil { return count, err } return count, nil }
go
func RunMigrations(cfg abcconfig.DBConfig, migrationsPath string) (int, error) { connStr, err := GetConnStr(cfg) if err != nil { return 0, err } count, err := mig.Up(cfg.DB, connStr, migrationsPath) if err != nil { return count, err } return count, nil }
[ "func", "RunMigrations", "(", "cfg", "abcconfig", ".", "DBConfig", ",", "migrationsPath", "string", ")", "(", "int", ",", "error", ")", "{", "connStr", ",", "err", ":=", "GetConnStr", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "count", ",", "err", ":=", "mig", ".", "Up", "(", "cfg", ".", "DB", ",", "connStr", ",", "migrationsPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "count", ",", "err", "\n", "}", "\n\n", "return", "count", ",", "nil", "\n", "}" ]
// RunMigrations executes the migrations "up" against the passed in database // and returns the number of migrations run.
[ "RunMigrations", "executes", "the", "migrations", "up", "against", "the", "passed", "in", "database", "and", "returns", "the", "number", "of", "migrations", "run", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcdatabase/database.go#L190-L202
15,645
volatiletech/abcweb
abcdatabase/database.go
ExecuteScript
func ExecuteScript(cfg abcconfig.DBConfig, script []byte) error { rdr := bytes.NewReader(script) if cfg.DB == "postgres" { passFilePath, err := pgPassFile(cfg) if err != nil { return err } defer os.Remove(passFilePath) cmd := exec.Command("psql", cfg.DBName, "-v", "ON_ERROR_STOP=1") cmd.Stdin = rdr cmd.Env = append(os.Environ(), pgEnv(cfg, passFilePath)...) res, err := cmd.CombinedOutput() if err != nil { fmt.Printf(string(res)) } return err } else if cfg.DB == "mysql" { passFile, err := mysqlPassFile(cfg) if err != nil { return err } defer os.Remove(passFile) cmd := exec.Command("mysql", fmt.Sprintf("--defaults-file=%s", passFile), "--database", cfg.DBName) cmd.Stdin = rdr res, err := cmd.CombinedOutput() if err != nil { fmt.Println(string(res)) } return err } return fmt.Errorf("cannot execute sql script, incompatible database %q", cfg.DB) }
go
func ExecuteScript(cfg abcconfig.DBConfig, script []byte) error { rdr := bytes.NewReader(script) if cfg.DB == "postgres" { passFilePath, err := pgPassFile(cfg) if err != nil { return err } defer os.Remove(passFilePath) cmd := exec.Command("psql", cfg.DBName, "-v", "ON_ERROR_STOP=1") cmd.Stdin = rdr cmd.Env = append(os.Environ(), pgEnv(cfg, passFilePath)...) res, err := cmd.CombinedOutput() if err != nil { fmt.Printf(string(res)) } return err } else if cfg.DB == "mysql" { passFile, err := mysqlPassFile(cfg) if err != nil { return err } defer os.Remove(passFile) cmd := exec.Command("mysql", fmt.Sprintf("--defaults-file=%s", passFile), "--database", cfg.DBName) cmd.Stdin = rdr res, err := cmd.CombinedOutput() if err != nil { fmt.Println(string(res)) } return err } return fmt.Errorf("cannot execute sql script, incompatible database %q", cfg.DB) }
[ "func", "ExecuteScript", "(", "cfg", "abcconfig", ".", "DBConfig", ",", "script", "[", "]", "byte", ")", "error", "{", "rdr", ":=", "bytes", ".", "NewReader", "(", "script", ")", "\n\n", "if", "cfg", ".", "DB", "==", "\"", "\"", "{", "passFilePath", ",", "err", ":=", "pgPassFile", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "os", ".", "Remove", "(", "passFilePath", ")", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "cfg", ".", "DBName", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Stdin", "=", "rdr", "\n", "cmd", ".", "Env", "=", "append", "(", "os", ".", "Environ", "(", ")", ",", "pgEnv", "(", "cfg", ",", "passFilePath", ")", "...", ")", "\n\n", "res", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "string", "(", "res", ")", ")", "\n", "}", "\n\n", "return", "err", "\n", "}", "else", "if", "cfg", ".", "DB", "==", "\"", "\"", "{", "passFile", ",", "err", ":=", "mysqlPassFile", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "os", ".", "Remove", "(", "passFile", ")", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "passFile", ")", ",", "\"", "\"", ",", "cfg", ".", "DBName", ")", "\n", "cmd", ".", "Stdin", "=", "rdr", "\n\n", "res", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "string", "(", "res", ")", ")", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cfg", ".", "DB", ")", "\n", "}" ]
// ExecuteScript executes the passed in SQL script against the passed in db
[ "ExecuteScript", "executes", "the", "passed", "in", "SQL", "script", "against", "the", "passed", "in", "db" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcdatabase/database.go#L244-L283
15,646
volatiletech/abcweb
abcdatabase/database.go
pgEnv
func pgEnv(cfg abcconfig.DBConfig, passFilePath string) []string { return []string{ fmt.Sprintf("PGHOST=%s", cfg.Host), fmt.Sprintf("PGPORT=%d", cfg.Port), fmt.Sprintf("PGUSER=%s", cfg.User), fmt.Sprintf("PGPASSFILE=%s", passFilePath), } }
go
func pgEnv(cfg abcconfig.DBConfig, passFilePath string) []string { return []string{ fmt.Sprintf("PGHOST=%s", cfg.Host), fmt.Sprintf("PGPORT=%d", cfg.Port), fmt.Sprintf("PGUSER=%s", cfg.User), fmt.Sprintf("PGPASSFILE=%s", passFilePath), } }
[ "func", "pgEnv", "(", "cfg", "abcconfig", ".", "DBConfig", ",", "passFilePath", "string", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cfg", ".", "Host", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cfg", ".", "Port", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cfg", ".", "User", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "passFilePath", ")", ",", "}", "\n", "}" ]
// pgEnv returns a slice of the connection related environment variables
[ "pgEnv", "returns", "a", "slice", "of", "the", "connection", "related", "environment", "variables" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcdatabase/database.go#L332-L339
15,647
volatiletech/abcweb
abcdatabase/database.go
pgPassFile
func pgPassFile(cfg abcconfig.DBConfig) (string, error) { tmp, err := ioutil.TempFile("", "pgpass") if err != nil { return "", errors.New("failed to create postgres pass file") } defer tmp.Close() fmt.Fprintf(tmp, "%s:%d:%s:%s", cfg.Host, cfg.Port, cfg.DBName, cfg.User) if len(cfg.Pass) != 0 { fmt.Fprintf(tmp, ":%s", cfg.Pass) } fmt.Fprintln(tmp) return tmp.Name(), nil }
go
func pgPassFile(cfg abcconfig.DBConfig) (string, error) { tmp, err := ioutil.TempFile("", "pgpass") if err != nil { return "", errors.New("failed to create postgres pass file") } defer tmp.Close() fmt.Fprintf(tmp, "%s:%d:%s:%s", cfg.Host, cfg.Port, cfg.DBName, cfg.User) if len(cfg.Pass) != 0 { fmt.Fprintf(tmp, ":%s", cfg.Pass) } fmt.Fprintln(tmp) return tmp.Name(), nil }
[ "func", "pgPassFile", "(", "cfg", "abcconfig", ".", "DBConfig", ")", "(", "string", ",", "error", ")", "{", "tmp", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "tmp", ".", "Close", "(", ")", "\n\n", "fmt", ".", "Fprintf", "(", "tmp", ",", "\"", "\"", ",", "cfg", ".", "Host", ",", "cfg", ".", "Port", ",", "cfg", ".", "DBName", ",", "cfg", ".", "User", ")", "\n", "if", "len", "(", "cfg", ".", "Pass", ")", "!=", "0", "{", "fmt", ".", "Fprintf", "(", "tmp", ",", "\"", "\"", ",", "cfg", ".", "Pass", ")", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "tmp", ")", "\n\n", "return", "tmp", ".", "Name", "(", ")", ",", "nil", "\n", "}" ]
// pgPassFile creates a file in the temp directory containing the connection // details and password for the database to be passed into the mysql cmdline cmd
[ "pgPassFile", "creates", "a", "file", "in", "the", "temp", "directory", "containing", "the", "connection", "details", "and", "password", "for", "the", "database", "to", "be", "passed", "into", "the", "mysql", "cmdline", "cmd" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcdatabase/database.go#L343-L357
15,648
volatiletech/abcweb
abcdatabase/database.go
mysqlPassFile
func mysqlPassFile(cfg abcconfig.DBConfig) (string, error) { tmp, err := ioutil.TempFile("", "mysqlpass") if err != nil { return "", errors.Wrap(err, "failed to create mysql pass file") } defer tmp.Close() fmt.Fprintln(tmp, "[client]") fmt.Fprintf(tmp, "host=%s\n", cfg.Host) fmt.Fprintf(tmp, "port=%d\n", cfg.Port) fmt.Fprintf(tmp, "user=%s\n", cfg.User) fmt.Fprintf(tmp, "password=%s\n", cfg.Pass) var sslMode string switch cfg.SSLMode { case "true": sslMode = "REQUIRED" case "false": sslMode = "DISABLED" default: sslMode = "PREFERRED" } fmt.Fprintf(tmp, "ssl-mode=%s\n", sslMode) return tmp.Name(), nil }
go
func mysqlPassFile(cfg abcconfig.DBConfig) (string, error) { tmp, err := ioutil.TempFile("", "mysqlpass") if err != nil { return "", errors.Wrap(err, "failed to create mysql pass file") } defer tmp.Close() fmt.Fprintln(tmp, "[client]") fmt.Fprintf(tmp, "host=%s\n", cfg.Host) fmt.Fprintf(tmp, "port=%d\n", cfg.Port) fmt.Fprintf(tmp, "user=%s\n", cfg.User) fmt.Fprintf(tmp, "password=%s\n", cfg.Pass) var sslMode string switch cfg.SSLMode { case "true": sslMode = "REQUIRED" case "false": sslMode = "DISABLED" default: sslMode = "PREFERRED" } fmt.Fprintf(tmp, "ssl-mode=%s\n", sslMode) return tmp.Name(), nil }
[ "func", "mysqlPassFile", "(", "cfg", "abcconfig", ".", "DBConfig", ")", "(", "string", ",", "error", ")", "{", "tmp", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "tmp", ".", "Close", "(", ")", "\n\n", "fmt", ".", "Fprintln", "(", "tmp", ",", "\"", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "tmp", ",", "\"", "\\n", "\"", ",", "cfg", ".", "Host", ")", "\n", "fmt", ".", "Fprintf", "(", "tmp", ",", "\"", "\\n", "\"", ",", "cfg", ".", "Port", ")", "\n", "fmt", ".", "Fprintf", "(", "tmp", ",", "\"", "\\n", "\"", ",", "cfg", ".", "User", ")", "\n", "fmt", ".", "Fprintf", "(", "tmp", ",", "\"", "\\n", "\"", ",", "cfg", ".", "Pass", ")", "\n\n", "var", "sslMode", "string", "\n", "switch", "cfg", ".", "SSLMode", "{", "case", "\"", "\"", ":", "sslMode", "=", "\"", "\"", "\n", "case", "\"", "\"", ":", "sslMode", "=", "\"", "\"", "\n", "default", ":", "sslMode", "=", "\"", "\"", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "tmp", ",", "\"", "\\n", "\"", ",", "sslMode", ")", "\n\n", "return", "tmp", ".", "Name", "(", ")", ",", "nil", "\n", "}" ]
// mysqlPassFile creates a file in the temp directory containing the connection // details and password for the database to be passed into the mysql cmdline cmd
[ "mysqlPassFile", "creates", "a", "file", "in", "the", "temp", "directory", "containing", "the", "connection", "details", "and", "password", "for", "the", "database", "to", "be", "passed", "into", "the", "mysql", "cmdline", "cmd" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcdatabase/database.go#L361-L387
15,649
volatiletech/abcweb
config/config.go
Initialize
func Initialize(env *pflag.Flag) (*Configuration, error) { c := &Configuration{} path, err := getAppPath() if err != nil { return nil, err } c.AppPath = path c.AppName = getAppName(c.AppPath) c.AppEnvName = strmangle.EnvAppName(c.AppName) c.ActiveEnv = getActiveEnv(c.AppPath, c.AppName) // If ActiveEnv is not set via env var or config file, // OR the user has passed in an override value through a flag, // then set it to the flag value. if env != nil && (c.ActiveEnv == "" || env.Changed) { c.ActiveEnv = env.Value.String() } c.ModeViper = NewModeViper(c.AppPath, c.AppEnvName, c.ActiveEnv) return c, nil }
go
func Initialize(env *pflag.Flag) (*Configuration, error) { c := &Configuration{} path, err := getAppPath() if err != nil { return nil, err } c.AppPath = path c.AppName = getAppName(c.AppPath) c.AppEnvName = strmangle.EnvAppName(c.AppName) c.ActiveEnv = getActiveEnv(c.AppPath, c.AppName) // If ActiveEnv is not set via env var or config file, // OR the user has passed in an override value through a flag, // then set it to the flag value. if env != nil && (c.ActiveEnv == "" || env.Changed) { c.ActiveEnv = env.Value.String() } c.ModeViper = NewModeViper(c.AppPath, c.AppEnvName, c.ActiveEnv) return c, nil }
[ "func", "Initialize", "(", "env", "*", "pflag", ".", "Flag", ")", "(", "*", "Configuration", ",", "error", ")", "{", "c", ":=", "&", "Configuration", "{", "}", "\n\n", "path", ",", "err", ":=", "getAppPath", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "AppPath", "=", "path", "\n\n", "c", ".", "AppName", "=", "getAppName", "(", "c", ".", "AppPath", ")", "\n", "c", ".", "AppEnvName", "=", "strmangle", ".", "EnvAppName", "(", "c", ".", "AppName", ")", "\n", "c", ".", "ActiveEnv", "=", "getActiveEnv", "(", "c", ".", "AppPath", ",", "c", ".", "AppName", ")", "\n", "// If ActiveEnv is not set via env var or config file,", "// OR the user has passed in an override value through a flag,", "// then set it to the flag value.", "if", "env", "!=", "nil", "&&", "(", "c", ".", "ActiveEnv", "==", "\"", "\"", "||", "env", ".", "Changed", ")", "{", "c", ".", "ActiveEnv", "=", "env", ".", "Value", ".", "String", "(", ")", "\n", "}", "\n", "c", ".", "ModeViper", "=", "NewModeViper", "(", "c", ".", "AppPath", ",", "c", ".", "AppEnvName", ",", "c", ".", "ActiveEnv", ")", "\n\n", "return", "c", ",", "nil", "\n", "}" ]
// Initialize the config
[ "Initialize", "the", "config" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/config/config.go#L55-L76
15,650
volatiletech/abcweb
config/config.go
InitializeP
func InitializeP(env *pflag.Flag) *Configuration { c, err := Initialize(env) if err != nil { panic(err) } return c }
go
func InitializeP(env *pflag.Flag) *Configuration { c, err := Initialize(env) if err != nil { panic(err) } return c }
[ "func", "InitializeP", "(", "env", "*", "pflag", ".", "Flag", ")", "*", "Configuration", "{", "c", ",", "err", ":=", "Initialize", "(", "env", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "return", "c", "\n", "}" ]
// InitializeP the config but panic if anything goes wrong
[ "InitializeP", "the", "config", "but", "panic", "if", "anything", "goes", "wrong" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/config/config.go#L79-L86
15,651
volatiletech/abcweb
config/config.go
getAppName
func getAppName(appPath string) string { // Is "/" on both Windows and Linux split := strings.Split(appPath, "/") return split[len(split)-1] }
go
func getAppName(appPath string) string { // Is "/" on both Windows and Linux split := strings.Split(appPath, "/") return split[len(split)-1] }
[ "func", "getAppName", "(", "appPath", "string", ")", "string", "{", "// Is \"/\" on both Windows and Linux", "split", ":=", "strings", ".", "Split", "(", "appPath", ",", "\"", "\"", ")", "\n", "return", "split", "[", "len", "(", "split", ")", "-", "1", "]", "\n", "}" ]
// getAppName gets the appname portion of a project path
[ "getAppName", "gets", "the", "appname", "portion", "of", "a", "project", "path" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/config/config.go#L201-L205
15,652
volatiletech/abcweb
config/config.go
CheckEnv
func (c *Configuration) CheckEnv() error { if c.ActiveEnv == "" { return fmt.Errorf("No active environment chosen. Please choose an environment using the \"env\" flag in config.toml or the $%s_ENV environment variable", c.AppEnvName) } return nil }
go
func (c *Configuration) CheckEnv() error { if c.ActiveEnv == "" { return fmt.Errorf("No active environment chosen. Please choose an environment using the \"env\" flag in config.toml or the $%s_ENV environment variable", c.AppEnvName) } return nil }
[ "func", "(", "c", "*", "Configuration", ")", "CheckEnv", "(", ")", "error", "{", "if", "c", ".", "ActiveEnv", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "c", ".", "AppEnvName", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckEnv outputs an error if no ActiveEnv is found
[ "CheckEnv", "outputs", "an", "error", "if", "no", "ActiveEnv", "is", "found" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/config/config.go#L219-L224
15,653
volatiletech/abcweb
abcmiddleware/errors.go
NewErrorManager
func NewErrorManager(render abcrender.Renderer) *errorManager { return &errorManager{ render: render, errors: []ErrorContainer{}, } }
go
func NewErrorManager(render abcrender.Renderer) *errorManager { return &errorManager{ render: render, errors: []ErrorContainer{}, } }
[ "func", "NewErrorManager", "(", "render", "abcrender", ".", "Renderer", ")", "*", "errorManager", "{", "return", "&", "errorManager", "{", "render", ":", "render", ",", "errors", ":", "[", "]", "ErrorContainer", "{", "}", ",", "}", "\n", "}" ]
// NewErrorManager creates an error manager that can be used to // create an error handler to wrap your controllers with
[ "NewErrorManager", "creates", "an", "error", "manager", "that", "can", "be", "used", "to", "create", "an", "error", "handler", "to", "wrap", "your", "controllers", "with" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcmiddleware/errors.go#L40-L45
15,654
volatiletech/abcweb
abcmiddleware/errors.go
Remove
func (m *errorManager) Remove(e ErrorContainer) { for i, v := range m.errors { if reflect.DeepEqual(v, e) { m.errors = append(m.errors[:i], m.errors[i+1:]...) } } }
go
func (m *errorManager) Remove(e ErrorContainer) { for i, v := range m.errors { if reflect.DeepEqual(v, e) { m.errors = append(m.errors[:i], m.errors[i+1:]...) } } }
[ "func", "(", "m", "*", "errorManager", ")", "Remove", "(", "e", "ErrorContainer", ")", "{", "for", "i", ",", "v", ":=", "range", "m", ".", "errors", "{", "if", "reflect", ".", "DeepEqual", "(", "v", ",", "e", ")", "{", "m", ".", "errors", "=", "append", "(", "m", ".", "errors", "[", ":", "i", "]", ",", "m", ".", "errors", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Remove a ErrorContainer from the error manager
[ "Remove", "a", "ErrorContainer", "from", "the", "error", "manager" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcmiddleware/errors.go#L70-L76
15,655
volatiletech/abcweb
abcmiddleware/errors.go
Add
func (m *errorManager) Add(e ErrorContainer) { m.errors = append(m.errors, e) }
go
func (m *errorManager) Add(e ErrorContainer) { m.errors = append(m.errors, e) }
[ "func", "(", "m", "*", "errorManager", ")", "Add", "(", "e", "ErrorContainer", ")", "{", "m", ".", "errors", "=", "append", "(", "m", ".", "errors", ",", "e", ")", "\n", "}" ]
// Add a new ErrorContainer to the error manager
[ "Add", "a", "new", "ErrorContainer", "to", "the", "error", "manager" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcmiddleware/errors.go#L79-L81
15,656
volatiletech/abcweb
abcsessions/middleware.go
Write
func (s *sessionsResponseWriter) Write(buf []byte) (int, error) { if !s.wroteHeader { s.WriteHeader(http.StatusOK) } return s.ResponseWriter.Write(buf) }
go
func (s *sessionsResponseWriter) Write(buf []byte) (int, error) { if !s.wroteHeader { s.WriteHeader(http.StatusOK) } return s.ResponseWriter.Write(buf) }
[ "func", "(", "s", "*", "sessionsResponseWriter", ")", "Write", "(", "buf", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "!", "s", ".", "wroteHeader", "{", "s", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "}", "\n", "return", "s", ".", "ResponseWriter", ".", "Write", "(", "buf", ")", "\n", "}" ]
// Write calls the underlying ResponseWriter Write func
[ "Write", "calls", "the", "underlying", "ResponseWriter", "Write", "func" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/middleware.go#L27-L32
15,657
volatiletech/abcweb
abcsessions/middleware.go
WriteHeader
func (s *sessionsResponseWriter) WriteHeader(code int) { s.wroteHeader = true // Set all the cookies in the cookie buffer if !s.wroteCookies { s.wroteCookies = true for _, c := range s.cookies { http.SetCookie(s.ResponseWriter, c) } } s.ResponseWriter.WriteHeader(code) }
go
func (s *sessionsResponseWriter) WriteHeader(code int) { s.wroteHeader = true // Set all the cookies in the cookie buffer if !s.wroteCookies { s.wroteCookies = true for _, c := range s.cookies { http.SetCookie(s.ResponseWriter, c) } } s.ResponseWriter.WriteHeader(code) }
[ "func", "(", "s", "*", "sessionsResponseWriter", ")", "WriteHeader", "(", "code", "int", ")", "{", "s", ".", "wroteHeader", "=", "true", "\n\n", "// Set all the cookies in the cookie buffer", "if", "!", "s", ".", "wroteCookies", "{", "s", ".", "wroteCookies", "=", "true", "\n", "for", "_", ",", "c", ":=", "range", "s", ".", "cookies", "{", "http", ".", "SetCookie", "(", "s", ".", "ResponseWriter", ",", "c", ")", "\n", "}", "\n", "}", "\n\n", "s", ".", "ResponseWriter", ".", "WriteHeader", "(", "code", ")", "\n", "}" ]
// WriteHeader sets all cookies in the buffer on the underlying ResponseWriter's // headers and calls the underlying ResponseWriter WriteHeader func
[ "WriteHeader", "sets", "all", "cookies", "in", "the", "buffer", "on", "the", "underlying", "ResponseWriter", "s", "headers", "and", "calls", "the", "underlying", "ResponseWriter", "WriteHeader", "func" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/middleware.go#L36-L48
15,658
volatiletech/abcweb
abcsessions/middleware.go
MiddlewareWithReset
func (m resetExpiryMiddleware) MiddlewareWithReset(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Convert the response writer to a sessions response, so we can // use its cookie buffering and writing capabilities w = newSessionsResponseWriter(w) err := m.resetter.ResetExpiry(w, r) // It's possible that the session hasn't been created yet // so there's nothing to reset. In that case, do not explode. if err != nil && !IsNoSessionError(err) { panic(err) } next.ServeHTTP(w, r) }) }
go
func (m resetExpiryMiddleware) MiddlewareWithReset(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Convert the response writer to a sessions response, so we can // use its cookie buffering and writing capabilities w = newSessionsResponseWriter(w) err := m.resetter.ResetExpiry(w, r) // It's possible that the session hasn't been created yet // so there's nothing to reset. In that case, do not explode. if err != nil && !IsNoSessionError(err) { panic(err) } next.ServeHTTP(w, r) }) }
[ "func", "(", "m", "resetExpiryMiddleware", ")", "MiddlewareWithReset", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Convert the response writer to a sessions response, so we can", "// use its cookie buffering and writing capabilities", "w", "=", "newSessionsResponseWriter", "(", "w", ")", "\n\n", "err", ":=", "m", ".", "resetter", ".", "ResetExpiry", "(", "w", ",", "r", ")", "\n", "// It's possible that the session hasn't been created yet", "// so there's nothing to reset. In that case, do not explode.", "if", "err", "!=", "nil", "&&", "!", "IsNoSessionError", "(", "err", ")", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// Middleware converts the ResponseWriter object to a sessionsResponseWriter // for buffering cookies across session API requests. // The sessionsResponseWriter implements cookieWriter. // // MiddlewareWithReset also resets the users session expiry on each request. // If you do not want this added functionality use Middleware instead.
[ "Middleware", "converts", "the", "ResponseWriter", "object", "to", "a", "sessionsResponseWriter", "for", "buffering", "cookies", "across", "session", "API", "requests", ".", "The", "sessionsResponseWriter", "implements", "cookieWriter", ".", "MiddlewareWithReset", "also", "resets", "the", "users", "session", "expiry", "on", "each", "request", ".", "If", "you", "do", "not", "want", "this", "added", "functionality", "use", "Middleware", "instead", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/middleware.go#L92-L107
15,659
volatiletech/abcweb
abcserver/server.go
Write
func (s serverErrLogger) Write(b []byte) (int, error) { s.log.Debug(string(b)) return 0, nil }
go
func (s serverErrLogger) Write(b []byte) (int, error) { s.log.Debug(string(b)) return 0, nil }
[ "func", "(", "s", "serverErrLogger", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "s", ".", "log", ".", "Debug", "(", "string", "(", "b", ")", ")", "\n", "return", "0", ",", "nil", "\n", "}" ]
// Implement Write to log server errors using the zap logger
[ "Implement", "Write", "to", "log", "server", "errors", "using", "the", "zap", "logger" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcserver/server.go#L26-L29
15,660
volatiletech/abcweb
abcserver/server.go
StartServer
func StartServer(cfg abcconfig.ServerConfig, router http.Handler, logger *zap.Logger) error { var err error server := http.Server{ ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, IdleTimeout: cfg.IdleTimeout, ErrorLog: log.New(serverErrLogger{logger}, "", 0), Handler: router, } server.TLSConfig = &tls.Config{ // Causes servers to use Go's default ciphersuite preferences, // which are tuned to avoid attacks. Does nothing on clients. PreferServerCipherSuites: true, // Only use curves which have assembly implementations CurvePreferences: []tls.CurveID{ tls.CurveP256, tls.X25519, // Go 1.8 only }, } // subscribe to SIGINT signals quit := make(chan os.Signal) signal.Notify(quit, os.Interrupt) // Start server graceful shutdown goroutine go func() { <-quit log.Println("Shutting down server...") if err := server.Shutdown(context.Background()); err != nil { log.Fatalf("could not shutdown: %v", err) } }() if len(cfg.TLSBind) > 0 { logger.Info("starting https listener", zap.String("bind", cfg.TLSBind)) server.Addr = cfg.TLSBind // Redirect http requests to https go Redirect(cfg, logger) if err := server.ListenAndServeTLS(cfg.TLSCertFile, cfg.TLSKeyFile); err != nil { fmt.Printf("failed to ListenAndServeTLS: %v", err) return nil } } else { logger.Info("starting http listener", zap.String("bind", cfg.Bind)) server.Addr = cfg.Bind if err := server.ListenAndServe(); err != nil { fmt.Printf("failed to ListenAndServe: %v", err) return nil } } return errors.Wrap(err, "failed to StartServer") }
go
func StartServer(cfg abcconfig.ServerConfig, router http.Handler, logger *zap.Logger) error { var err error server := http.Server{ ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, IdleTimeout: cfg.IdleTimeout, ErrorLog: log.New(serverErrLogger{logger}, "", 0), Handler: router, } server.TLSConfig = &tls.Config{ // Causes servers to use Go's default ciphersuite preferences, // which are tuned to avoid attacks. Does nothing on clients. PreferServerCipherSuites: true, // Only use curves which have assembly implementations CurvePreferences: []tls.CurveID{ tls.CurveP256, tls.X25519, // Go 1.8 only }, } // subscribe to SIGINT signals quit := make(chan os.Signal) signal.Notify(quit, os.Interrupt) // Start server graceful shutdown goroutine go func() { <-quit log.Println("Shutting down server...") if err := server.Shutdown(context.Background()); err != nil { log.Fatalf("could not shutdown: %v", err) } }() if len(cfg.TLSBind) > 0 { logger.Info("starting https listener", zap.String("bind", cfg.TLSBind)) server.Addr = cfg.TLSBind // Redirect http requests to https go Redirect(cfg, logger) if err := server.ListenAndServeTLS(cfg.TLSCertFile, cfg.TLSKeyFile); err != nil { fmt.Printf("failed to ListenAndServeTLS: %v", err) return nil } } else { logger.Info("starting http listener", zap.String("bind", cfg.Bind)) server.Addr = cfg.Bind if err := server.ListenAndServe(); err != nil { fmt.Printf("failed to ListenAndServe: %v", err) return nil } } return errors.Wrap(err, "failed to StartServer") }
[ "func", "StartServer", "(", "cfg", "abcconfig", ".", "ServerConfig", ",", "router", "http", ".", "Handler", ",", "logger", "*", "zap", ".", "Logger", ")", "error", "{", "var", "err", "error", "\n", "server", ":=", "http", ".", "Server", "{", "ReadTimeout", ":", "cfg", ".", "ReadTimeout", ",", "WriteTimeout", ":", "cfg", ".", "WriteTimeout", ",", "IdleTimeout", ":", "cfg", ".", "IdleTimeout", ",", "ErrorLog", ":", "log", ".", "New", "(", "serverErrLogger", "{", "logger", "}", ",", "\"", "\"", ",", "0", ")", ",", "Handler", ":", "router", ",", "}", "\n\n", "server", ".", "TLSConfig", "=", "&", "tls", ".", "Config", "{", "// Causes servers to use Go's default ciphersuite preferences,", "// which are tuned to avoid attacks. Does nothing on clients.", "PreferServerCipherSuites", ":", "true", ",", "// Only use curves which have assembly implementations", "CurvePreferences", ":", "[", "]", "tls", ".", "CurveID", "{", "tls", ".", "CurveP256", ",", "tls", ".", "X25519", ",", "// Go 1.8 only", "}", ",", "}", "\n\n", "// subscribe to SIGINT signals", "quit", ":=", "make", "(", "chan", "os", ".", "Signal", ")", "\n", "signal", ".", "Notify", "(", "quit", ",", "os", ".", "Interrupt", ")", "\n\n", "// Start server graceful shutdown goroutine", "go", "func", "(", ")", "{", "<-", "quit", "\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "server", ".", "Shutdown", "(", "context", ".", "Background", "(", ")", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "if", "len", "(", "cfg", ".", "TLSBind", ")", ">", "0", "{", "logger", ".", "Info", "(", "\"", "\"", ",", "zap", ".", "String", "(", "\"", "\"", ",", "cfg", ".", "TLSBind", ")", ")", "\n", "server", ".", "Addr", "=", "cfg", ".", "TLSBind", "\n\n", "// Redirect http requests to https", "go", "Redirect", "(", "cfg", ",", "logger", ")", "\n\n", "if", "err", ":=", "server", ".", "ListenAndServeTLS", "(", "cfg", ".", "TLSCertFile", ",", "cfg", ".", "TLSKeyFile", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "else", "{", "logger", ".", "Info", "(", "\"", "\"", ",", "zap", ".", "String", "(", "\"", "\"", ",", "cfg", ".", "Bind", ")", ")", "\n", "server", ".", "Addr", "=", "cfg", ".", "Bind", "\n", "if", "err", ":=", "server", ".", "ListenAndServe", "(", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// StartServer starts the web server on the specified port, and can be // gracefully shut down by sending an os.Interrupt signal to the server. // This is a blocking call.
[ "StartServer", "starts", "the", "web", "server", "on", "the", "specified", "port", "and", "can", "be", "gracefully", "shut", "down", "by", "sending", "an", "os", ".", "Interrupt", "signal", "to", "the", "server", ".", "This", "is", "a", "blocking", "call", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcserver/server.go#L34-L89
15,661
volatiletech/abcweb
abcserver/server.go
Redirect
func Redirect(cfg abcconfig.ServerConfig, logger *zap.Logger) { var err error // Get https port from TLS Bind _, httpsPort, err := net.SplitHostPort(cfg.TLSBind) if err != nil { log.Fatal("failed to get port from tls bind", zap.Error(err)) } logger.Info("starting http -> https redirect listener", zap.String("bind", cfg.Bind)) server := http.Server{ Addr: cfg.Bind, // Do not set IdleTimeout, so Go uses ReadTimeout value. // IdleTimeout config value too high for redirect listener. ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, ErrorLog: log.New(serverErrLogger{logger}, "", 0), Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Remove port if it exists so we can replace it with https port httpHost := r.Host if strings.ContainsRune(r.Host, ':') { httpHost, _, err = net.SplitHostPort(r.Host) if err != nil { logger.Error("failed to get http host from request", zap.String("host", r.Host), zap.Error(err)) w.WriteHeader(http.StatusBadRequest) io.WriteString(w, "invalid host header") return } } var url string if httpsPort != "443" { url = fmt.Sprintf("https://%s:%s%s", httpHost, httpsPort, r.RequestURI) } else { url = fmt.Sprintf("https://%s%s", httpHost, r.RequestURI) } logger.Info("redirect", zap.String("host", r.Host), zap.String("path", r.URL.String()), zap.String("redirecturl", url)) http.Redirect(w, r, url, http.StatusMovedPermanently) }), } // Start permanent listener err = server.ListenAndServe() logger.Fatal("http redirect listener failed", zap.Error(err)) }
go
func Redirect(cfg abcconfig.ServerConfig, logger *zap.Logger) { var err error // Get https port from TLS Bind _, httpsPort, err := net.SplitHostPort(cfg.TLSBind) if err != nil { log.Fatal("failed to get port from tls bind", zap.Error(err)) } logger.Info("starting http -> https redirect listener", zap.String("bind", cfg.Bind)) server := http.Server{ Addr: cfg.Bind, // Do not set IdleTimeout, so Go uses ReadTimeout value. // IdleTimeout config value too high for redirect listener. ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, ErrorLog: log.New(serverErrLogger{logger}, "", 0), Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Remove port if it exists so we can replace it with https port httpHost := r.Host if strings.ContainsRune(r.Host, ':') { httpHost, _, err = net.SplitHostPort(r.Host) if err != nil { logger.Error("failed to get http host from request", zap.String("host", r.Host), zap.Error(err)) w.WriteHeader(http.StatusBadRequest) io.WriteString(w, "invalid host header") return } } var url string if httpsPort != "443" { url = fmt.Sprintf("https://%s:%s%s", httpHost, httpsPort, r.RequestURI) } else { url = fmt.Sprintf("https://%s%s", httpHost, r.RequestURI) } logger.Info("redirect", zap.String("host", r.Host), zap.String("path", r.URL.String()), zap.String("redirecturl", url)) http.Redirect(w, r, url, http.StatusMovedPermanently) }), } // Start permanent listener err = server.ListenAndServe() logger.Fatal("http redirect listener failed", zap.Error(err)) }
[ "func", "Redirect", "(", "cfg", "abcconfig", ".", "ServerConfig", ",", "logger", "*", "zap", ".", "Logger", ")", "{", "var", "err", "error", "\n\n", "// Get https port from TLS Bind", "_", ",", "httpsPort", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "cfg", ".", "TLSBind", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "\"", "\"", ",", "zap", ".", "Error", "(", "err", ")", ")", "\n", "}", "\n\n", "logger", ".", "Info", "(", "\"", "\"", ",", "zap", ".", "String", "(", "\"", "\"", ",", "cfg", ".", "Bind", ")", ")", "\n\n", "server", ":=", "http", ".", "Server", "{", "Addr", ":", "cfg", ".", "Bind", ",", "// Do not set IdleTimeout, so Go uses ReadTimeout value.", "// IdleTimeout config value too high for redirect listener.", "ReadTimeout", ":", "cfg", ".", "ReadTimeout", ",", "WriteTimeout", ":", "cfg", ".", "WriteTimeout", ",", "ErrorLog", ":", "log", ".", "New", "(", "serverErrLogger", "{", "logger", "}", ",", "\"", "\"", ",", "0", ")", ",", "Handler", ":", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Remove port if it exists so we can replace it with https port", "httpHost", ":=", "r", ".", "Host", "\n", "if", "strings", ".", "ContainsRune", "(", "r", ".", "Host", ",", "':'", ")", "{", "httpHost", ",", "_", ",", "err", "=", "net", ".", "SplitHostPort", "(", "r", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"", "\"", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Host", ")", ",", "zap", ".", "Error", "(", "err", ")", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "io", ".", "WriteString", "(", "w", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "var", "url", "string", "\n", "if", "httpsPort", "!=", "\"", "\"", "{", "url", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "httpHost", ",", "httpsPort", ",", "r", ".", "RequestURI", ")", "\n", "}", "else", "{", "url", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "httpHost", ",", "r", ".", "RequestURI", ")", "\n", "}", "\n\n", "logger", ".", "Info", "(", "\"", "\"", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "Host", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "r", ".", "URL", ".", "String", "(", ")", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "url", ")", ")", "\n", "http", ".", "Redirect", "(", "w", ",", "r", ",", "url", ",", "http", ".", "StatusMovedPermanently", ")", "\n", "}", ")", ",", "}", "\n\n", "// Start permanent listener", "err", "=", "server", ".", "ListenAndServe", "(", ")", "\n", "logger", ".", "Fatal", "(", "\"", "\"", ",", "zap", ".", "Error", "(", "err", ")", ")", "\n", "}" ]
// Redirect listens on the non-https port, and redirects all requests to https
[ "Redirect", "listens", "on", "the", "non", "-", "https", "port", "and", "redirects", "all", "requests", "to", "https" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcserver/server.go#L92-L138
15,662
volatiletech/abcweb
abcsessions/memory.go
NewMemoryStorer
func NewMemoryStorer(maxAge, cleanInterval time.Duration) (*MemoryStorer, error) { if (maxAge != 0 && cleanInterval == 0) || (cleanInterval != 0 && maxAge == 0) { panic("if max age or clean interval is set, the other must also be set") } m := &MemoryStorer{ sessions: make(map[string]memorySession), maxAge: maxAge, cleanInterval: cleanInterval, } return m, nil }
go
func NewMemoryStorer(maxAge, cleanInterval time.Duration) (*MemoryStorer, error) { if (maxAge != 0 && cleanInterval == 0) || (cleanInterval != 0 && maxAge == 0) { panic("if max age or clean interval is set, the other must also be set") } m := &MemoryStorer{ sessions: make(map[string]memorySession), maxAge: maxAge, cleanInterval: cleanInterval, } return m, nil }
[ "func", "NewMemoryStorer", "(", "maxAge", ",", "cleanInterval", "time", ".", "Duration", ")", "(", "*", "MemoryStorer", ",", "error", ")", "{", "if", "(", "maxAge", "!=", "0", "&&", "cleanInterval", "==", "0", ")", "||", "(", "cleanInterval", "!=", "0", "&&", "maxAge", "==", "0", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "m", ":=", "&", "MemoryStorer", "{", "sessions", ":", "make", "(", "map", "[", "string", "]", "memorySession", ")", ",", "maxAge", ":", "maxAge", ",", "cleanInterval", ":", "cleanInterval", ",", "}", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// NewMemoryStorer initializes and returns a new MemoryStorer object. // It takes the maxAge of how long each session should live in memory, // and a cleanInterval duration which defines how often the clean // task should check for maxAge sessions to be removed from memory. // Persistent storage can be attained by setting maxAge and cleanInterval // to zero, however the memory will be wiped when the server is restarted.
[ "NewMemoryStorer", "initializes", "and", "returns", "a", "new", "MemoryStorer", "object", ".", "It", "takes", "the", "maxAge", "of", "how", "long", "each", "session", "should", "live", "in", "memory", "and", "a", "cleanInterval", "duration", "which", "defines", "how", "often", "the", "clean", "task", "should", "check", "for", "maxAge", "sessions", "to", "be", "removed", "from", "memory", ".", "Persistent", "storage", "can", "be", "attained", "by", "setting", "maxAge", "and", "cleanInterval", "to", "zero", "however", "the", "memory", "will", "be", "wiped", "when", "the", "server", "is", "restarted", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/memory.go#L44-L56
15,663
volatiletech/abcweb
abcsessions/memory.go
All
func (m *MemoryStorer) All() ([]string, error) { m.mut.RLock() defer m.mut.RUnlock() sessions := make([]string, len(m.sessions)) i := 0 for id := range m.sessions { sessions[i] = id i++ } return sessions, nil }
go
func (m *MemoryStorer) All() ([]string, error) { m.mut.RLock() defer m.mut.RUnlock() sessions := make([]string, len(m.sessions)) i := 0 for id := range m.sessions { sessions[i] = id i++ } return sessions, nil }
[ "func", "(", "m", "*", "MemoryStorer", ")", "All", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "m", ".", "mut", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mut", ".", "RUnlock", "(", ")", "\n\n", "sessions", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "m", ".", "sessions", ")", ")", "\n\n", "i", ":=", "0", "\n", "for", "id", ":=", "range", "m", ".", "sessions", "{", "sessions", "[", "i", "]", "=", "id", "\n", "i", "++", "\n", "}", "\n\n", "return", "sessions", ",", "nil", "\n", "}" ]
// All keys in the memory store
[ "All", "keys", "in", "the", "memory", "store" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/memory.go#L59-L72
15,664
volatiletech/abcweb
abcsessions/memory.go
Clean
func (m *MemoryStorer) Clean() { t := time.Now().UTC() m.mut.Lock() for id, session := range m.sessions { if t.After(session.expires) { delete(m.sessions, id) } } m.mut.Unlock() }
go
func (m *MemoryStorer) Clean() { t := time.Now().UTC() m.mut.Lock() for id, session := range m.sessions { if t.After(session.expires) { delete(m.sessions, id) } } m.mut.Unlock() }
[ "func", "(", "m", "*", "MemoryStorer", ")", "Clean", "(", ")", "{", "t", ":=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n", "m", ".", "mut", ".", "Lock", "(", ")", "\n", "for", "id", ",", "session", ":=", "range", "m", ".", "sessions", "{", "if", "t", ".", "After", "(", "session", ".", "expires", ")", "{", "delete", "(", "m", ".", "sessions", ",", "id", ")", "\n", "}", "\n", "}", "\n", "m", ".", "mut", ".", "Unlock", "(", ")", "\n", "}" ]
// Clean checks all sessions in memory to see if they are older than // maxAge by checking their expiry. If it finds an expired session // it will remove it from memory.
[ "Clean", "checks", "all", "sessions", "in", "memory", "to", "see", "if", "they", "are", "older", "than", "maxAge", "by", "checking", "their", "expiry", ".", "If", "it", "finds", "an", "expired", "session", "it", "will", "remove", "it", "from", "memory", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/memory.go#L125-L134
15,665
volatiletech/abcweb
abcsessions/memory.go
StartCleaner
func (m *MemoryStorer) StartCleaner() { if m.maxAge == 0 || m.cleanInterval == 0 { panic("both max age and clean interval must be set to non-zero") } // init quit chan m.quit = make(chan struct{}) m.wg.Add(1) // Start the cleaner infinite loop go routine. // StopCleaner() can be used to kill this go routine. go m.cleanerLoop() }
go
func (m *MemoryStorer) StartCleaner() { if m.maxAge == 0 || m.cleanInterval == 0 { panic("both max age and clean interval must be set to non-zero") } // init quit chan m.quit = make(chan struct{}) m.wg.Add(1) // Start the cleaner infinite loop go routine. // StopCleaner() can be used to kill this go routine. go m.cleanerLoop() }
[ "func", "(", "m", "*", "MemoryStorer", ")", "StartCleaner", "(", ")", "{", "if", "m", ".", "maxAge", "==", "0", "||", "m", ".", "cleanInterval", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// init quit chan", "m", ".", "quit", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "m", ".", "wg", ".", "Add", "(", "1", ")", "\n\n", "// Start the cleaner infinite loop go routine.", "// StopCleaner() can be used to kill this go routine.", "go", "m", ".", "cleanerLoop", "(", ")", "\n", "}" ]
// StartCleaner starts the memory session cleaner go routine. This go routine // will delete expired sessions from the memory map on the cleanInterval interval.
[ "StartCleaner", "starts", "the", "memory", "session", "cleaner", "go", "routine", ".", "This", "go", "routine", "will", "delete", "expired", "sessions", "from", "the", "memory", "map", "on", "the", "cleanInterval", "interval", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/memory.go#L138-L151
15,666
volatiletech/abcweb
cmd/generate.go
modelsCmdPreRun
func modelsCmdPreRun(cmd *cobra.Command, args []string) error { var err error cnf, err = config.Initialize(cmd.Flags().Lookup("env")) if err != nil { return err } cnf.ModeViper.BindPFlags(modelsCmd.Flags()) err = cnf.CheckEnv() if err != nil { return err } return modelsCmdSetup(cmd, args) }
go
func modelsCmdPreRun(cmd *cobra.Command, args []string) error { var err error cnf, err = config.Initialize(cmd.Flags().Lookup("env")) if err != nil { return err } cnf.ModeViper.BindPFlags(modelsCmd.Flags()) err = cnf.CheckEnv() if err != nil { return err } return modelsCmdSetup(cmd, args) }
[ "func", "modelsCmdPreRun", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "var", "err", "error", "\n", "cnf", ",", "err", "=", "config", ".", "Initialize", "(", "cmd", ".", "Flags", "(", ")", ".", "Lookup", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cnf", ".", "ModeViper", ".", "BindPFlags", "(", "modelsCmd", ".", "Flags", "(", ")", ")", "\n\n", "err", "=", "cnf", ".", "CheckEnv", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "modelsCmdSetup", "(", "cmd", ",", "args", ")", "\n", "}" ]
// modelsCmdPreRun sets up the modelsCmdState and modelsCmdConfig objects
[ "modelsCmdPreRun", "sets", "up", "the", "modelsCmdState", "and", "modelsCmdConfig", "objects" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/cmd/generate.go#L136-L151
15,667
volatiletech/abcweb
strmangle/strmangle.go
replaceNonAlpha
func replaceNonAlpha(s string, replace byte) string { byts := []byte(s) newByts := make([]byte, len(byts)) for i := 0; i < len(byts); i++ { if byts[i] < 'A' || (byts[i] > 'Z' && byts[i] < 'a') || byts[i] > 'z' { newByts[i] = replace } else { newByts[i] = byts[i] } } return string(newByts) }
go
func replaceNonAlpha(s string, replace byte) string { byts := []byte(s) newByts := make([]byte, len(byts)) for i := 0; i < len(byts); i++ { if byts[i] < 'A' || (byts[i] > 'Z' && byts[i] < 'a') || byts[i] > 'z' { newByts[i] = replace } else { newByts[i] = byts[i] } } return string(newByts) }
[ "func", "replaceNonAlpha", "(", "s", "string", ",", "replace", "byte", ")", "string", "{", "byts", ":=", "[", "]", "byte", "(", "s", ")", "\n", "newByts", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "byts", ")", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "byts", ")", ";", "i", "++", "{", "if", "byts", "[", "i", "]", "<", "'A'", "||", "(", "byts", "[", "i", "]", ">", "'Z'", "&&", "byts", "[", "i", "]", "<", "'a'", ")", "||", "byts", "[", "i", "]", ">", "'z'", "{", "newByts", "[", "i", "]", "=", "replace", "\n", "}", "else", "{", "newByts", "[", "i", "]", "=", "byts", "[", "i", "]", "\n", "}", "\n", "}", "\n\n", "return", "string", "(", "newByts", ")", "\n", "}" ]
// replaceNonAlpha replaces non alphabet characters with the replace byte.
[ "replaceNonAlpha", "replaces", "non", "alphabet", "characters", "with", "the", "replace", "byte", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/strmangle/strmangle.go#L43-L56
15,668
volatiletech/abcweb
cmd/dev.go
startGulp
func startGulp(publicPathEnv string, ctx context.Context) error { _, err := os.Stat(filepath.Join(cnf.AppPath, "gulpfile.js")) if os.IsNotExist(err) { fmt.Println("No gulpfile.js present, skipping gulp watch") return nil } else if err != nil { return err } _, err = exec.LookPath("gulp") if err != nil { fmt.Println("Cannot find gulp in PATH. Is it installed?") return nil } cmd := exec.Command("gulp", "watch") cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout cmd.Env = append([]string{publicPathEnv}, os.Environ()...) return cmd.Run() }
go
func startGulp(publicPathEnv string, ctx context.Context) error { _, err := os.Stat(filepath.Join(cnf.AppPath, "gulpfile.js")) if os.IsNotExist(err) { fmt.Println("No gulpfile.js present, skipping gulp watch") return nil } else if err != nil { return err } _, err = exec.LookPath("gulp") if err != nil { fmt.Println("Cannot find gulp in PATH. Is it installed?") return nil } cmd := exec.Command("gulp", "watch") cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout cmd.Env = append([]string{publicPathEnv}, os.Environ()...) return cmd.Run() }
[ "func", "startGulp", "(", "publicPathEnv", "string", ",", "ctx", "context", ".", "Context", ")", "error", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "cnf", ".", "AppPath", ",", "\"", "\"", ")", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "exec", ".", "LookPath", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "cmd", ".", "Stdin", "=", "os", ".", "Stdin", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "cmd", ".", "Env", "=", "append", "(", "[", "]", "string", "{", "publicPathEnv", "}", ",", "os", ".", "Environ", "(", ")", "...", ")", "\n\n", "return", "cmd", ".", "Run", "(", ")", "\n", "}" ]
// startGulp starts "gulp watch" if it can find gulpfile.js and the gulp command.
[ "startGulp", "starts", "gulp", "watch", "if", "it", "can", "find", "gulpfile", ".", "js", "and", "the", "gulp", "command", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/cmd/dev.go#L118-L141
15,669
volatiletech/abcweb
cmd/dev.go
startRefresh
func startRefresh(publicPathEnv string, ctx context.Context) (*refresh.Manager, error) { cfgFile := filepath.Join(cnf.AppPath, "watch.toml") _, err := os.Stat(cfgFile) if err != nil && !os.IsNotExist(err) { return nil, err } c := &refreshConfig{ AppRoot: ".", IgnoredFolders: []string{"vendor", "log", "logs", "tmp", "node_modules", "bin", "templates"}, IncludedExtensions: []string{".go", ".toml"}, BuildPath: os.TempDir(), BuildDelay: 200, BinaryName: "watch-build", CommandFlags: []string{}, CommandEnv: []string{ fmt.Sprintf("%s_ENV=%s", cnf.AppEnvName, cnf.ActiveEnv), }, EnableColors: true, } // Only read the config file if it exists, otherwise use the defaults above. if !os.IsNotExist(err) { _, err = toml.DecodeFile(cfgFile, c) if err != nil { return nil, err } } // Append the APPNAME_SERVER_PUBLIC_PATH environment var to refresh libs CommandEnv. c.CommandEnv = append(c.CommandEnv, publicPathEnv) rc := &refresh.Configuration{ AppRoot: c.AppRoot, IgnoredFolders: c.IgnoredFolders, IncludedExtensions: c.IncludedExtensions, BuildPath: c.BuildPath, BuildDelay: c.BuildDelay, BinaryName: c.BinaryName, CommandFlags: c.CommandFlags, CommandEnv: c.CommandEnv, EnableColors: c.EnableColors, LogName: c.LogName, } r := refresh.NewWithContext(rc, ctx) return r, nil }
go
func startRefresh(publicPathEnv string, ctx context.Context) (*refresh.Manager, error) { cfgFile := filepath.Join(cnf.AppPath, "watch.toml") _, err := os.Stat(cfgFile) if err != nil && !os.IsNotExist(err) { return nil, err } c := &refreshConfig{ AppRoot: ".", IgnoredFolders: []string{"vendor", "log", "logs", "tmp", "node_modules", "bin", "templates"}, IncludedExtensions: []string{".go", ".toml"}, BuildPath: os.TempDir(), BuildDelay: 200, BinaryName: "watch-build", CommandFlags: []string{}, CommandEnv: []string{ fmt.Sprintf("%s_ENV=%s", cnf.AppEnvName, cnf.ActiveEnv), }, EnableColors: true, } // Only read the config file if it exists, otherwise use the defaults above. if !os.IsNotExist(err) { _, err = toml.DecodeFile(cfgFile, c) if err != nil { return nil, err } } // Append the APPNAME_SERVER_PUBLIC_PATH environment var to refresh libs CommandEnv. c.CommandEnv = append(c.CommandEnv, publicPathEnv) rc := &refresh.Configuration{ AppRoot: c.AppRoot, IgnoredFolders: c.IgnoredFolders, IncludedExtensions: c.IncludedExtensions, BuildPath: c.BuildPath, BuildDelay: c.BuildDelay, BinaryName: c.BinaryName, CommandFlags: c.CommandFlags, CommandEnv: c.CommandEnv, EnableColors: c.EnableColors, LogName: c.LogName, } r := refresh.NewWithContext(rc, ctx) return r, nil }
[ "func", "startRefresh", "(", "publicPathEnv", "string", ",", "ctx", "context", ".", "Context", ")", "(", "*", "refresh", ".", "Manager", ",", "error", ")", "{", "cfgFile", ":=", "filepath", ".", "Join", "(", "cnf", ".", "AppPath", ",", "\"", "\"", ")", "\n\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "cfgFile", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "c", ":=", "&", "refreshConfig", "{", "AppRoot", ":", "\"", "\"", ",", "IgnoredFolders", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "IncludedExtensions", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "BuildPath", ":", "os", ".", "TempDir", "(", ")", ",", "BuildDelay", ":", "200", ",", "BinaryName", ":", "\"", "\"", ",", "CommandFlags", ":", "[", "]", "string", "{", "}", ",", "CommandEnv", ":", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cnf", ".", "AppEnvName", ",", "cnf", ".", "ActiveEnv", ")", ",", "}", ",", "EnableColors", ":", "true", ",", "}", "\n\n", "// Only read the config file if it exists, otherwise use the defaults above.", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "_", ",", "err", "=", "toml", ".", "DecodeFile", "(", "cfgFile", ",", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Append the APPNAME_SERVER_PUBLIC_PATH environment var to refresh libs CommandEnv.", "c", ".", "CommandEnv", "=", "append", "(", "c", ".", "CommandEnv", ",", "publicPathEnv", ")", "\n\n", "rc", ":=", "&", "refresh", ".", "Configuration", "{", "AppRoot", ":", "c", ".", "AppRoot", ",", "IgnoredFolders", ":", "c", ".", "IgnoredFolders", ",", "IncludedExtensions", ":", "c", ".", "IncludedExtensions", ",", "BuildPath", ":", "c", ".", "BuildPath", ",", "BuildDelay", ":", "c", ".", "BuildDelay", ",", "BinaryName", ":", "c", ".", "BinaryName", ",", "CommandFlags", ":", "c", ".", "CommandFlags", ",", "CommandEnv", ":", "c", ".", "CommandEnv", ",", "EnableColors", ":", "c", ".", "EnableColors", ",", "LogName", ":", "c", ".", "LogName", ",", "}", "\n\n", "r", ":=", "refresh", ".", "NewWithContext", "(", "rc", ",", "ctx", ")", "\n\n", "return", "r", ",", "nil", "\n", "}" ]
// startRefresh starts the refresh server to watch go files for recompilation.
[ "startRefresh", "starts", "the", "refresh", "server", "to", "watch", "go", "files", "for", "recompilation", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/cmd/dev.go#L159-L208
15,670
volatiletech/abcweb
abcsessions/sessions.go
IsNoSessionError
func IsNoSessionError(err error) bool { _, ok := err.(noSessionInterface) if ok { return ok } _, ok = errors.Cause(err).(noSessionInterface) return ok }
go
func IsNoSessionError(err error) bool { _, ok := err.(noSessionInterface) if ok { return ok } _, ok = errors.Cause(err).(noSessionInterface) return ok }
[ "func", "IsNoSessionError", "(", "err", "error", ")", "bool", "{", "_", ",", "ok", ":=", "err", ".", "(", "noSessionInterface", ")", "\n", "if", "ok", "{", "return", "ok", "\n", "}", "\n\n", "_", ",", "ok", "=", "errors", ".", "Cause", "(", "err", ")", ".", "(", "noSessionInterface", ")", "\n", "return", "ok", "\n", "}" ]
// IsNoSessionError checks an error to see if it means that there was no session
[ "IsNoSessionError", "checks", "an", "error", "to", "see", "if", "it", "means", "that", "there", "was", "no", "session" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/sessions.go#L85-L93
15,671
volatiletech/abcweb
abcsessions/sessions.go
IsNoMapKeyError
func IsNoMapKeyError(err error) bool { _, ok := err.(noMapKeyInterface) if ok { return ok } _, ok = errors.Cause(err).(noMapKeyInterface) return ok }
go
func IsNoMapKeyError(err error) bool { _, ok := err.(noMapKeyInterface) if ok { return ok } _, ok = errors.Cause(err).(noMapKeyInterface) return ok }
[ "func", "IsNoMapKeyError", "(", "err", "error", ")", "bool", "{", "_", ",", "ok", ":=", "err", ".", "(", "noMapKeyInterface", ")", "\n", "if", "ok", "{", "return", "ok", "\n", "}", "\n\n", "_", ",", "ok", "=", "errors", ".", "Cause", "(", "err", ")", ".", "(", "noMapKeyInterface", ")", "\n", "return", "ok", "\n", "}" ]
// IsNoMapKeyError checks an error to see if it means that there was // no session map key
[ "IsNoMapKeyError", "checks", "an", "error", "to", "see", "if", "it", "means", "that", "there", "was", "no", "session", "map", "key" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/sessions.go#L97-L105
15,672
volatiletech/abcweb
abcsessions/sessions.go
Set
func Set(overseer Overseer, w http.ResponseWriter, r *http.Request, key string, value string) error { var sess session sessMap := make(map[string]string) val, err := overseer.Get(w, r) if err != nil && !IsNoSessionError(err) { return errors.Wrap(err, "unable to get session") } if !IsNoSessionError(err) { err = json.Unmarshal([]byte(val), &sess) if err != nil { return errors.Wrap(err, "unable to unmarshal session object") } if sess.Value != nil { err = json.Unmarshal(*sess.Value, &sessMap) if err != nil { return errors.Wrap(err, "unable to unmarshal session map value") } } } sessMap[key] = value mv, err := json.Marshal(sessMap) if err != nil { return errors.Wrap(err, "unable to marshal session map value") } sess.Value = (*json.RawMessage)(&mv) ret, err := json.Marshal(sess) if err != nil { return errors.Wrap(err, "unable to marshal session object") } return overseer.Set(w, r, string(ret)) }
go
func Set(overseer Overseer, w http.ResponseWriter, r *http.Request, key string, value string) error { var sess session sessMap := make(map[string]string) val, err := overseer.Get(w, r) if err != nil && !IsNoSessionError(err) { return errors.Wrap(err, "unable to get session") } if !IsNoSessionError(err) { err = json.Unmarshal([]byte(val), &sess) if err != nil { return errors.Wrap(err, "unable to unmarshal session object") } if sess.Value != nil { err = json.Unmarshal(*sess.Value, &sessMap) if err != nil { return errors.Wrap(err, "unable to unmarshal session map value") } } } sessMap[key] = value mv, err := json.Marshal(sessMap) if err != nil { return errors.Wrap(err, "unable to marshal session map value") } sess.Value = (*json.RawMessage)(&mv) ret, err := json.Marshal(sess) if err != nil { return errors.Wrap(err, "unable to marshal session object") } return overseer.Set(w, r, string(ret)) }
[ "func", "Set", "(", "overseer", "Overseer", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "key", "string", ",", "value", "string", ")", "error", "{", "var", "sess", "session", "\n", "sessMap", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n\n", "val", ",", "err", ":=", "overseer", ".", "Get", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "IsNoSessionError", "(", "err", ")", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "IsNoSessionError", "(", "err", ")", "{", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "val", ")", ",", "&", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "sess", ".", "Value", "!=", "nil", "{", "err", "=", "json", ".", "Unmarshal", "(", "*", "sess", ".", "Value", ",", "&", "sessMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "sessMap", "[", "key", "]", "=", "value", "\n\n", "mv", ",", "err", ":=", "json", ".", "Marshal", "(", "sessMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "sess", ".", "Value", "=", "(", "*", "json", ".", "RawMessage", ")", "(", "&", "mv", ")", "\n\n", "ret", ",", "err", ":=", "json", ".", "Marshal", "(", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "overseer", ".", "Set", "(", "w", ",", "r", ",", "string", "(", "ret", ")", ")", "\n", "}" ]
// Set is a JSON helper used for storing key-value session values. // Set modifies the marshalled map stored in the session to include the key value pair passed in.
[ "Set", "is", "a", "JSON", "helper", "used", "for", "storing", "key", "-", "value", "session", "values", ".", "Set", "modifies", "the", "marshalled", "map", "stored", "in", "the", "session", "to", "include", "the", "key", "value", "pair", "passed", "in", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/sessions.go#L154-L191
15,673
volatiletech/abcweb
abcsessions/sessions.go
Get
func Get(overseer Overseer, w http.ResponseWriter, r *http.Request, key string) (string, error) { val, err := overseer.Get(w, r) if err != nil { return "", errors.Wrap(err, "unable to get session") } var sess session err = json.Unmarshal([]byte(val), &sess) if err != nil { return "", errors.Wrap(err, "unable to unmarshal session object") } var sessMap map[string]string err = json.Unmarshal(*sess.Value, &sessMap) if err != nil { return "", errors.Wrap(err, "unable to unmarshal session map value") } mapVal, ok := sessMap[key] if !ok { return "", errNoMapKey{} } return mapVal, nil }
go
func Get(overseer Overseer, w http.ResponseWriter, r *http.Request, key string) (string, error) { val, err := overseer.Get(w, r) if err != nil { return "", errors.Wrap(err, "unable to get session") } var sess session err = json.Unmarshal([]byte(val), &sess) if err != nil { return "", errors.Wrap(err, "unable to unmarshal session object") } var sessMap map[string]string err = json.Unmarshal(*sess.Value, &sessMap) if err != nil { return "", errors.Wrap(err, "unable to unmarshal session map value") } mapVal, ok := sessMap[key] if !ok { return "", errNoMapKey{} } return mapVal, nil }
[ "func", "Get", "(", "overseer", "Overseer", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "key", "string", ")", "(", "string", ",", "error", ")", "{", "val", ",", "err", ":=", "overseer", ".", "Get", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "sess", "session", "\n", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "val", ")", ",", "&", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "sessMap", "map", "[", "string", "]", "string", "\n", "err", "=", "json", ".", "Unmarshal", "(", "*", "sess", ".", "Value", ",", "&", "sessMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "mapVal", ",", "ok", ":=", "sessMap", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "errNoMapKey", "{", "}", "\n", "}", "\n\n", "return", "mapVal", ",", "nil", "\n", "}" ]
// Get is a JSON helper used for retrieving key-value session values. // Get returns the value pointed to by the key of the marshalled map stored in the session.
[ "Get", "is", "a", "JSON", "helper", "used", "for", "retrieving", "key", "-", "value", "session", "values", ".", "Get", "returns", "the", "value", "pointed", "to", "by", "the", "key", "of", "the", "marshalled", "map", "stored", "in", "the", "session", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/sessions.go#L195-L219
15,674
volatiletech/abcweb
abcsessions/sessions.go
GetObj
func GetObj(overseer Overseer, w http.ResponseWriter, r *http.Request, pointer interface{}) error { val, err := overseer.Get(w, r) if err != nil { return errors.Wrap(err, "unable to get session") } var sess session // json unmarshal the outter session struct err = json.Unmarshal([]byte(val), &sess) if err != nil { return errors.Wrap(err, "unable to unmarshal session object") } // json unmarshal the RawMessage value into the users pointer err = json.Unmarshal(*sess.Value, pointer) return errors.Wrap(err, "unable to unmarshal session value into pointer") }
go
func GetObj(overseer Overseer, w http.ResponseWriter, r *http.Request, pointer interface{}) error { val, err := overseer.Get(w, r) if err != nil { return errors.Wrap(err, "unable to get session") } var sess session // json unmarshal the outter session struct err = json.Unmarshal([]byte(val), &sess) if err != nil { return errors.Wrap(err, "unable to unmarshal session object") } // json unmarshal the RawMessage value into the users pointer err = json.Unmarshal(*sess.Value, pointer) return errors.Wrap(err, "unable to unmarshal session value into pointer") }
[ "func", "GetObj", "(", "overseer", "Overseer", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "pointer", "interface", "{", "}", ")", "error", "{", "val", ",", "err", ":=", "overseer", ".", "Get", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "sess", "session", "\n", "// json unmarshal the outter session struct", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "val", ")", ",", "&", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// json unmarshal the RawMessage value into the users pointer", "err", "=", "json", ".", "Unmarshal", "(", "*", "sess", ".", "Value", ",", "pointer", ")", "\n", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// GetObj is a JSON helper used for retrieving object or variable session values. // GetObj unmarshals the session value into the pointer pointed to by pointer.
[ "GetObj", "is", "a", "JSON", "helper", "used", "for", "retrieving", "object", "or", "variable", "session", "values", ".", "GetObj", "unmarshals", "the", "session", "value", "into", "the", "pointer", "pointed", "to", "by", "pointer", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/sessions.go#L296-L312
15,675
volatiletech/abcweb
abcsessions/sessions.go
GetFlash
func GetFlash(overseer Overseer, w http.ResponseWriter, r *http.Request, key string) (string, error) { var sess session val, err := overseer.Get(w, r) if err != nil { return "", errors.Wrap(err, "unable to get session") } err = json.Unmarshal([]byte(val), &sess) if err != nil { return "", errors.Wrap(err, "unable to unmarshal session object") } fv, ok := sess.Flash[key] if !ok { return "", errNoMapKey{} } var ret string err = json.Unmarshal(*fv, &ret) if err != nil { return ret, errors.Wrap(err, "unable to unmarshal flash value") } delete(sess.Flash, key) mv, err := json.Marshal(sess) if err != nil { return ret, errors.Wrap(err, "unable to marshal session object") } err = overseer.Set(w, r, string(mv)) return ret, errors.Wrap(err, "unable to set flash session object") }
go
func GetFlash(overseer Overseer, w http.ResponseWriter, r *http.Request, key string) (string, error) { var sess session val, err := overseer.Get(w, r) if err != nil { return "", errors.Wrap(err, "unable to get session") } err = json.Unmarshal([]byte(val), &sess) if err != nil { return "", errors.Wrap(err, "unable to unmarshal session object") } fv, ok := sess.Flash[key] if !ok { return "", errNoMapKey{} } var ret string err = json.Unmarshal(*fv, &ret) if err != nil { return ret, errors.Wrap(err, "unable to unmarshal flash value") } delete(sess.Flash, key) mv, err := json.Marshal(sess) if err != nil { return ret, errors.Wrap(err, "unable to marshal session object") } err = overseer.Set(w, r, string(mv)) return ret, errors.Wrap(err, "unable to set flash session object") }
[ "func", "GetFlash", "(", "overseer", "Overseer", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "key", "string", ")", "(", "string", ",", "error", ")", "{", "var", "sess", "session", "\n\n", "val", ",", "err", ":=", "overseer", ".", "Get", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "val", ")", ",", "&", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "fv", ",", "ok", ":=", "sess", ".", "Flash", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "errNoMapKey", "{", "}", "\n", "}", "\n\n", "var", "ret", "string", "\n", "err", "=", "json", ".", "Unmarshal", "(", "*", "fv", ",", "&", "ret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ret", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "delete", "(", "sess", ".", "Flash", ",", "key", ")", "\n\n", "mv", ",", "err", ":=", "json", ".", "Marshal", "(", "sess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ret", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "err", "=", "overseer", ".", "Set", "(", "w", ",", "r", ",", "string", "(", "mv", ")", ")", "\n", "return", "ret", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// GetFlash retrieves a flash message from the session then deletes it
[ "GetFlash", "retrieves", "a", "flash", "message", "from", "the", "session", "then", "deletes", "it" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/sessions.go#L347-L380
15,676
volatiletech/abcweb
abcsessions/sessions.go
AddFlashObj
func AddFlashObj(overseer Overseer, w http.ResponseWriter, r *http.Request, key string, value interface{}) error { mv, err := json.Marshal(value) if err != nil { return errors.Wrap(err, "unable to marshal flash value") } return AddFlash(overseer, w, r, key, string(mv)) }
go
func AddFlashObj(overseer Overseer, w http.ResponseWriter, r *http.Request, key string, value interface{}) error { mv, err := json.Marshal(value) if err != nil { return errors.Wrap(err, "unable to marshal flash value") } return AddFlash(overseer, w, r, key, string(mv)) }
[ "func", "AddFlashObj", "(", "overseer", "Overseer", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "key", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "mv", ",", "err", ":=", "json", ".", "Marshal", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "AddFlash", "(", "overseer", ",", "w", ",", "r", ",", "key", ",", "string", "(", "mv", ")", ")", "\n", "}" ]
// AddFlashObj adds a flash message to the session that will be deleted when it is retrieved with GetFlash
[ "AddFlashObj", "adds", "a", "flash", "message", "to", "the", "session", "that", "will", "be", "deleted", "when", "it", "is", "retrieved", "with", "GetFlash" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/sessions.go#L383-L390
15,677
volatiletech/abcweb
abcsessions/sessions.go
GetFlashObj
func GetFlashObj(overseer Overseer, w http.ResponseWriter, r *http.Request, key string, pointer interface{}) error { val, err := GetFlash(overseer, w, r, key) if err != nil { return errors.Wrap(err, "unable to get flash object") } return json.Unmarshal([]byte(val), pointer) }
go
func GetFlashObj(overseer Overseer, w http.ResponseWriter, r *http.Request, key string, pointer interface{}) error { val, err := GetFlash(overseer, w, r, key) if err != nil { return errors.Wrap(err, "unable to get flash object") } return json.Unmarshal([]byte(val), pointer) }
[ "func", "GetFlashObj", "(", "overseer", "Overseer", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "key", "string", ",", "pointer", "interface", "{", "}", ")", "error", "{", "val", ",", "err", ":=", "GetFlash", "(", "overseer", ",", "w", ",", "r", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "val", ")", ",", "pointer", ")", "\n", "}" ]
// GetFlashObj unmarshals a flash message from the session into the users pointer // then deletes it from the session.
[ "GetFlashObj", "unmarshals", "a", "flash", "message", "from", "the", "session", "into", "the", "users", "pointer", "then", "deletes", "it", "from", "the", "session", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/sessions.go#L394-L401
15,678
volatiletech/abcweb
abcsessions/disk.go
NewDiskStorer
func NewDiskStorer(folderPath string, maxAge, cleanInterval time.Duration) (*DiskStorer, error) { if (maxAge != 0 && cleanInterval == 0) || (cleanInterval != 0 && maxAge == 0) { panic("if max age or clean interval is set, the other must also be set") } d := &DiskStorer{ folderPath: folderPath, maxAge: maxAge, cleanInterval: cleanInterval, } // Create the storage folder if it does not exist _, err := os.Stat(folderPath) if os.IsNotExist(err) { err := os.Mkdir(folderPath, os.FileMode(int(0755))) if err != nil { return nil, errors.Wrapf(err, "unable to make directory: %s", folderPath) } } return d, nil }
go
func NewDiskStorer(folderPath string, maxAge, cleanInterval time.Duration) (*DiskStorer, error) { if (maxAge != 0 && cleanInterval == 0) || (cleanInterval != 0 && maxAge == 0) { panic("if max age or clean interval is set, the other must also be set") } d := &DiskStorer{ folderPath: folderPath, maxAge: maxAge, cleanInterval: cleanInterval, } // Create the storage folder if it does not exist _, err := os.Stat(folderPath) if os.IsNotExist(err) { err := os.Mkdir(folderPath, os.FileMode(int(0755))) if err != nil { return nil, errors.Wrapf(err, "unable to make directory: %s", folderPath) } } return d, nil }
[ "func", "NewDiskStorer", "(", "folderPath", "string", ",", "maxAge", ",", "cleanInterval", "time", ".", "Duration", ")", "(", "*", "DiskStorer", ",", "error", ")", "{", "if", "(", "maxAge", "!=", "0", "&&", "cleanInterval", "==", "0", ")", "||", "(", "cleanInterval", "!=", "0", "&&", "maxAge", "==", "0", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "d", ":=", "&", "DiskStorer", "{", "folderPath", ":", "folderPath", ",", "maxAge", ":", "maxAge", ",", "cleanInterval", ":", "cleanInterval", ",", "}", "\n\n", "// Create the storage folder if it does not exist", "_", ",", "err", ":=", "os", ".", "Stat", "(", "folderPath", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", ":=", "os", ".", "Mkdir", "(", "folderPath", ",", "os", ".", "FileMode", "(", "int", "(", "0755", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "folderPath", ")", "\n", "}", "\n", "}", "\n\n", "return", "d", ",", "nil", "\n", "}" ]
// NewDiskStorer initializes and returns a new DiskStorer object. // It takes the maxAge of how long each session should live on disk, // and a cleanInterval duration which defines how often the clean // task should check for maxAge expired sessions to be removed from disk. // Persistent storage can be attained by setting maxAge and cleanInterval // to zero.
[ "NewDiskStorer", "initializes", "and", "returns", "a", "new", "DiskStorer", "object", ".", "It", "takes", "the", "maxAge", "of", "how", "long", "each", "session", "should", "live", "on", "disk", "and", "a", "cleanInterval", "duration", "which", "defines", "how", "often", "the", "clean", "task", "should", "check", "for", "maxAge", "expired", "sessions", "to", "be", "removed", "from", "disk", ".", "Persistent", "storage", "can", "be", "attained", "by", "setting", "maxAge", "and", "cleanInterval", "to", "zero", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/disk.go#L48-L69
15,679
volatiletech/abcweb
abcsessions/disk.go
All
func (d *DiskStorer) All() ([]string, error) { files, err := ioutil.ReadDir(d.folderPath) if err != nil { return []string{}, errors.Wrapf(err, "unable to read directory: %s", d.folderPath) } sessions := make([]string, len(files)) for i := 0; i < len(files); i++ { sessions[i] = files[i].Name() } return sessions, nil }
go
func (d *DiskStorer) All() ([]string, error) { files, err := ioutil.ReadDir(d.folderPath) if err != nil { return []string{}, errors.Wrapf(err, "unable to read directory: %s", d.folderPath) } sessions := make([]string, len(files)) for i := 0; i < len(files); i++ { sessions[i] = files[i].Name() } return sessions, nil }
[ "func", "(", "d", "*", "DiskStorer", ")", "All", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "d", ".", "folderPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "string", "{", "}", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "d", ".", "folderPath", ")", "\n", "}", "\n\n", "sessions", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "files", ")", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "files", ")", ";", "i", "++", "{", "sessions", "[", "i", "]", "=", "files", "[", "i", "]", ".", "Name", "(", ")", "\n", "}", "\n\n", "return", "sessions", ",", "nil", "\n", "}" ]
// All keys in the disk store
[ "All", "keys", "in", "the", "disk", "store" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/disk.go#L72-L85
15,680
volatiletech/abcweb
abcsessions/disk.go
StartCleaner
func (d *DiskStorer) StartCleaner() { if d.maxAge == 0 || d.cleanInterval == 0 { panic("both max age and clean interval must be set to non-zero") } // init quit chan d.quit = make(chan struct{}) d.wg.Add(1) // Start the cleaner infinite loop go routine. // StopCleaner() can be used to kill this go routine. go d.cleanerLoop() }
go
func (d *DiskStorer) StartCleaner() { if d.maxAge == 0 || d.cleanInterval == 0 { panic("both max age and clean interval must be set to non-zero") } // init quit chan d.quit = make(chan struct{}) d.wg.Add(1) // Start the cleaner infinite loop go routine. // StopCleaner() can be used to kill this go routine. go d.cleanerLoop() }
[ "func", "(", "d", "*", "DiskStorer", ")", "StartCleaner", "(", ")", "{", "if", "d", ".", "maxAge", "==", "0", "||", "d", ".", "cleanInterval", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// init quit chan", "d", ".", "quit", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "d", ".", "wg", ".", "Add", "(", "1", ")", "\n\n", "// Start the cleaner infinite loop go routine.", "// StopCleaner() can be used to kill this go routine.", "go", "d", ".", "cleanerLoop", "(", ")", "\n", "}" ]
// StartCleaner starts the disk session cleaner go routine. This go routine // will delete expired disk sessions on the cleanInterval interval.
[ "StartCleaner", "starts", "the", "disk", "session", "cleaner", "go", "routine", ".", "This", "go", "routine", "will", "delete", "expired", "disk", "sessions", "on", "the", "cleanInterval", "interval", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/disk.go#L167-L180
15,681
volatiletech/abcweb
abcsessions/disk.go
Clean
func (d *DiskStorer) Clean() { t := time.Now().UTC() files, err := ioutil.ReadDir(d.folderPath) if err != nil { panic(err) } for _, file := range files { tspec := times.Get(file) // File is expired if tspec.AccessTime().UTC().UTC().Add(d.maxAge).Before(t) { filePath := path.Join(d.folderPath, file.Name()) d.mut.Lock() _, err := os.Stat(filePath) // If the file has been deleted manually from the server // in between the time we read the directory and now, it will // fail here with a ErrNotExist. If so, continue gracefully. // It would be innefficient to hold a lock for the duration of // the loop, so we only lock when we find an expired file. if os.IsNotExist(err) { d.mut.Unlock() continue } else if err != nil { panic(err) } err = os.Remove(filePath) d.mut.Unlock() if err != nil { panic(err) } } } }
go
func (d *DiskStorer) Clean() { t := time.Now().UTC() files, err := ioutil.ReadDir(d.folderPath) if err != nil { panic(err) } for _, file := range files { tspec := times.Get(file) // File is expired if tspec.AccessTime().UTC().UTC().Add(d.maxAge).Before(t) { filePath := path.Join(d.folderPath, file.Name()) d.mut.Lock() _, err := os.Stat(filePath) // If the file has been deleted manually from the server // in between the time we read the directory and now, it will // fail here with a ErrNotExist. If so, continue gracefully. // It would be innefficient to hold a lock for the duration of // the loop, so we only lock when we find an expired file. if os.IsNotExist(err) { d.mut.Unlock() continue } else if err != nil { panic(err) } err = os.Remove(filePath) d.mut.Unlock() if err != nil { panic(err) } } } }
[ "func", "(", "d", "*", "DiskStorer", ")", "Clean", "(", ")", "{", "t", ":=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "d", ".", "folderPath", ")", "\n\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "file", ":=", "range", "files", "{", "tspec", ":=", "times", ".", "Get", "(", "file", ")", "\n\n", "// File is expired", "if", "tspec", ".", "AccessTime", "(", ")", ".", "UTC", "(", ")", ".", "UTC", "(", ")", ".", "Add", "(", "d", ".", "maxAge", ")", ".", "Before", "(", "t", ")", "{", "filePath", ":=", "path", ".", "Join", "(", "d", ".", "folderPath", ",", "file", ".", "Name", "(", ")", ")", "\n\n", "d", ".", "mut", ".", "Lock", "(", ")", "\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filePath", ")", "\n", "// If the file has been deleted manually from the server", "// in between the time we read the directory and now, it will", "// fail here with a ErrNotExist. If so, continue gracefully.", "// It would be innefficient to hold a lock for the duration of", "// the loop, so we only lock when we find an expired file.", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "d", ".", "mut", ".", "Unlock", "(", ")", "\n", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "os", ".", "Remove", "(", "filePath", ")", "\n", "d", ".", "mut", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Clean checks all session files on disk to see if they are older than // maxAge by checking their access time. If it finds an expired session file // it will remove it from disk.
[ "Clean", "checks", "all", "session", "files", "on", "disk", "to", "see", "if", "they", "are", "older", "than", "maxAge", "by", "checking", "their", "access", "time", ".", "If", "it", "finds", "an", "expired", "session", "file", "it", "will", "remove", "it", "from", "disk", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/disk.go#L202-L239
15,682
volatiletech/abcweb
abcsessions/storage_overseer.go
NewStorageOverseer
func NewStorageOverseer(opts CookieOptions, storer Storer) *StorageOverseer { if len(opts.Name) == 0 { panic("cookie name must be provided") } o := &StorageOverseer{ Storer: storer, options: opts, } o.resetExpiryMiddleware.resetter = o return o }
go
func NewStorageOverseer(opts CookieOptions, storer Storer) *StorageOverseer { if len(opts.Name) == 0 { panic("cookie name must be provided") } o := &StorageOverseer{ Storer: storer, options: opts, } o.resetExpiryMiddleware.resetter = o return o }
[ "func", "NewStorageOverseer", "(", "opts", "CookieOptions", ",", "storer", "Storer", ")", "*", "StorageOverseer", "{", "if", "len", "(", "opts", ".", "Name", ")", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "o", ":=", "&", "StorageOverseer", "{", "Storer", ":", "storer", ",", "options", ":", "opts", ",", "}", "\n\n", "o", ".", "resetExpiryMiddleware", ".", "resetter", "=", "o", "\n\n", "return", "o", "\n", "}" ]
// NewStorageOverseer returns a new storage overseer
[ "NewStorageOverseer", "returns", "a", "new", "storage", "overseer" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/storage_overseer.go#L18-L31
15,683
volatiletech/abcweb
abcsessions/storage_overseer.go
Get
func (s *StorageOverseer) Get(w http.ResponseWriter, r *http.Request) (value string, err error) { sessID, err := s.options.getCookieValue(w, r) if err != nil { return "", errors.Wrap(err, "unable to get session id from cookie") } val, err := s.Storer.Get(sessID) if err != nil { return "", errors.Wrap(err, "unable to get session value") } return val, nil }
go
func (s *StorageOverseer) Get(w http.ResponseWriter, r *http.Request) (value string, err error) { sessID, err := s.options.getCookieValue(w, r) if err != nil { return "", errors.Wrap(err, "unable to get session id from cookie") } val, err := s.Storer.Get(sessID) if err != nil { return "", errors.Wrap(err, "unable to get session value") } return val, nil }
[ "func", "(", "s", "*", "StorageOverseer", ")", "Get", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "value", "string", ",", "err", "error", ")", "{", "sessID", ",", "err", ":=", "s", ".", "options", ".", "getCookieValue", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "val", ",", "err", ":=", "s", ".", "Storer", ".", "Get", "(", "sessID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "val", ",", "nil", "\n", "}" ]
// Get looks in the cookie for the session ID and retrieves the value string stored in the session.
[ "Get", "looks", "in", "the", "cookie", "for", "the", "session", "ID", "and", "retrieves", "the", "value", "string", "stored", "in", "the", "session", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/storage_overseer.go#L34-L46
15,684
volatiletech/abcweb
abcsessions/storage_overseer.go
Set
func (s *StorageOverseer) Set(w http.ResponseWriter, r *http.Request, value string) error { // Reuse the existing cookie ID if it exists sessID, _ := s.options.getCookieValue(w, r) if len(sessID) == 0 { sessID = uuid.NewV4().String() } err := s.Storer.Set(sessID, value) if err != nil { return errors.Wrap(err, "unable to set session value") } w.(cookieWriter).SetCookie(s.options.makeCookie(sessID)) return nil }
go
func (s *StorageOverseer) Set(w http.ResponseWriter, r *http.Request, value string) error { // Reuse the existing cookie ID if it exists sessID, _ := s.options.getCookieValue(w, r) if len(sessID) == 0 { sessID = uuid.NewV4().String() } err := s.Storer.Set(sessID, value) if err != nil { return errors.Wrap(err, "unable to set session value") } w.(cookieWriter).SetCookie(s.options.makeCookie(sessID)) return nil }
[ "func", "(", "s", "*", "StorageOverseer", ")", "Set", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "value", "string", ")", "error", "{", "// Reuse the existing cookie ID if it exists", "sessID", ",", "_", ":=", "s", ".", "options", ".", "getCookieValue", "(", "w", ",", "r", ")", "\n\n", "if", "len", "(", "sessID", ")", "==", "0", "{", "sessID", "=", "uuid", ".", "NewV4", "(", ")", ".", "String", "(", ")", "\n", "}", "\n\n", "err", ":=", "s", ".", "Storer", ".", "Set", "(", "sessID", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "w", ".", "(", "cookieWriter", ")", ".", "SetCookie", "(", "s", ".", "options", ".", "makeCookie", "(", "sessID", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// Set looks in the cookie for the session ID and modifies the session with the new value. // If the session does not exist it creates a new one.
[ "Set", "looks", "in", "the", "cookie", "for", "the", "session", "ID", "and", "modifies", "the", "session", "with", "the", "new", "value", ".", "If", "the", "session", "does", "not", "exist", "it", "creates", "a", "new", "one", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/storage_overseer.go#L50-L66
15,685
volatiletech/abcweb
abcsessions/storage_overseer.go
Del
func (s *StorageOverseer) Del(w http.ResponseWriter, r *http.Request) error { sessID, err := s.options.getCookieValue(w, r) if err != nil { return nil } s.options.deleteCookie(w) err = s.Storer.Del(sessID) if IsNoSessionError(err) { return nil } else if err != nil { return errors.Wrap(err, "unable to delete server-side session") } return nil }
go
func (s *StorageOverseer) Del(w http.ResponseWriter, r *http.Request) error { sessID, err := s.options.getCookieValue(w, r) if err != nil { return nil } s.options.deleteCookie(w) err = s.Storer.Del(sessID) if IsNoSessionError(err) { return nil } else if err != nil { return errors.Wrap(err, "unable to delete server-side session") } return nil }
[ "func", "(", "s", "*", "StorageOverseer", ")", "Del", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "error", "{", "sessID", ",", "err", ":=", "s", ".", "options", ".", "getCookieValue", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "s", ".", "options", ".", "deleteCookie", "(", "w", ")", "\n\n", "err", "=", "s", ".", "Storer", ".", "Del", "(", "sessID", ")", "\n", "if", "IsNoSessionError", "(", "err", ")", "{", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Del deletes the session if it exists and sets the session cookie to expire instantly.
[ "Del", "deletes", "the", "session", "if", "it", "exists", "and", "sets", "the", "session", "cookie", "to", "expire", "instantly", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/storage_overseer.go#L69-L85
15,686
volatiletech/abcweb
abcsessions/storage_overseer.go
Regenerate
func (s *StorageOverseer) Regenerate(w http.ResponseWriter, r *http.Request) error { id, err := s.options.getCookieValue(w, r) if err != nil { return errors.Wrap(err, "unable to get session id from cookie") } val, err := s.Storer.Get(id) if err != nil { return errors.Wrap(err, "unable to get session value") } // Delete the old session _ = s.Storer.Del(id) // Generate a new ID id = uuid.NewV4().String() // Create a new session with the old value if err = s.Storer.Set(id, val); err != nil { return errors.Wrap(err, "unable to set session value") } // Override the old cookie with the new cookie w.(cookieWriter).SetCookie(s.options.makeCookie(id)) return nil }
go
func (s *StorageOverseer) Regenerate(w http.ResponseWriter, r *http.Request) error { id, err := s.options.getCookieValue(w, r) if err != nil { return errors.Wrap(err, "unable to get session id from cookie") } val, err := s.Storer.Get(id) if err != nil { return errors.Wrap(err, "unable to get session value") } // Delete the old session _ = s.Storer.Del(id) // Generate a new ID id = uuid.NewV4().String() // Create a new session with the old value if err = s.Storer.Set(id, val); err != nil { return errors.Wrap(err, "unable to set session value") } // Override the old cookie with the new cookie w.(cookieWriter).SetCookie(s.options.makeCookie(id)) return nil }
[ "func", "(", "s", "*", "StorageOverseer", ")", "Regenerate", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "error", "{", "id", ",", "err", ":=", "s", ".", "options", ".", "getCookieValue", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "val", ",", "err", ":=", "s", ".", "Storer", ".", "Get", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Delete the old session", "_", "=", "s", ".", "Storer", ".", "Del", "(", "id", ")", "\n\n", "// Generate a new ID", "id", "=", "uuid", ".", "NewV4", "(", ")", ".", "String", "(", ")", "\n\n", "// Create a new session with the old value", "if", "err", "=", "s", ".", "Storer", ".", "Set", "(", "id", ",", "val", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Override the old cookie with the new cookie", "w", ".", "(", "cookieWriter", ")", ".", "SetCookie", "(", "s", ".", "options", ".", "makeCookie", "(", "id", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// Regenerate a new session ID for your current session
[ "Regenerate", "a", "new", "session", "ID", "for", "your", "current", "session" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/storage_overseer.go#L88-L114
15,687
volatiletech/abcweb
abcsessions/storage_overseer.go
SessionID
func (s *StorageOverseer) SessionID(w http.ResponseWriter, r *http.Request) (string, error) { return s.options.getCookieValue(w, r) }
go
func (s *StorageOverseer) SessionID(w http.ResponseWriter, r *http.Request) (string, error) { return s.options.getCookieValue(w, r) }
[ "func", "(", "s", "*", "StorageOverseer", ")", "SessionID", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "return", "s", ".", "options", ".", "getCookieValue", "(", "w", ",", "r", ")", "\n", "}" ]
// SessionID returns the session ID stored in the cookie's value field. // It will return a errNoSession error if no session exists.
[ "SessionID", "returns", "the", "session", "ID", "stored", "in", "the", "cookie", "s", "value", "field", ".", "It", "will", "return", "a", "errNoSession", "error", "if", "no", "session", "exists", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/storage_overseer.go#L118-L120
15,688
volatiletech/abcweb
abcrender/render.go
HTML
func (r *Render) HTML(w io.Writer, status int, name string, binding interface{}) error { return r.Render.HTML(w, status, name, binding) }
go
func (r *Render) HTML(w io.Writer, status int, name string, binding interface{}) error { return r.Render.HTML(w, status, name, binding) }
[ "func", "(", "r", "*", "Render", ")", "HTML", "(", "w", "io", ".", "Writer", ",", "status", "int", ",", "name", "string", ",", "binding", "interface", "{", "}", ")", "error", "{", "return", "r", ".", "Render", ".", "HTML", "(", "w", ",", "status", ",", "name", ",", "binding", ")", "\n", "}" ]
// HTML renders a HTML template by calling unrolled Render package's HTML function
[ "HTML", "renders", "a", "HTML", "template", "by", "calling", "unrolled", "Render", "package", "s", "HTML", "function" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L47-L49
15,689
volatiletech/abcweb
abcrender/render.go
HTMLWithLayout
func (r *Render) HTMLWithLayout(w io.Writer, status int, name string, binding interface{}, layout string) error { return r.Render.HTML(w, status, name, binding, render.HTMLOptions{Layout: layout}) }
go
func (r *Render) HTMLWithLayout(w io.Writer, status int, name string, binding interface{}, layout string) error { return r.Render.HTML(w, status, name, binding, render.HTMLOptions{Layout: layout}) }
[ "func", "(", "r", "*", "Render", ")", "HTMLWithLayout", "(", "w", "io", ".", "Writer", ",", "status", "int", ",", "name", "string", ",", "binding", "interface", "{", "}", ",", "layout", "string", ")", "error", "{", "return", "r", ".", "Render", ".", "HTML", "(", "w", ",", "status", ",", "name", ",", "binding", ",", "render", ".", "HTMLOptions", "{", "Layout", ":", "layout", "}", ")", "\n", "}" ]
// HTMLWithLayout renders a HTML template using a specified layout file by calling // unrolled Render package's HTML function with a HTMLOptions argument
[ "HTMLWithLayout", "renders", "a", "HTML", "template", "using", "a", "specified", "layout", "file", "by", "calling", "unrolled", "Render", "package", "s", "HTML", "function", "with", "a", "HTMLOptions", "argument" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L53-L55
15,690
volatiletech/abcweb
abcrender/render.go
New
func New(opts render.Options, manifest map[string]string) Renderer { return &Render{ Render: render.New(opts), assetsManifest: manifest, } }
go
func New(opts render.Options, manifest map[string]string) Renderer { return &Render{ Render: render.New(opts), assetsManifest: manifest, } }
[ "func", "New", "(", "opts", "render", ".", "Options", ",", "manifest", "map", "[", "string", "]", "string", ")", "Renderer", "{", "return", "&", "Render", "{", "Render", ":", "render", ".", "New", "(", "opts", ")", ",", "assetsManifest", ":", "manifest", ",", "}", "\n", "}" ]
// New returns a new Render with AssetsManifest and Render set
[ "New", "returns", "a", "new", "Render", "with", "AssetsManifest", "and", "Render", "set" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L58-L63
15,691
volatiletech/abcweb
abcrender/render.go
GetManifest
func GetManifest(publicPath string) (map[string]string, error) { manifestPath := filepath.Join(publicPath, "assets", "manifest.json") contents, err := ioutil.ReadFile(manifestPath) if err != nil { return nil, err } if len(contents) == 0 { return nil, errors.New("manifest.json is empty") } manifest := map[string]string{} err = json.Unmarshal(contents, &manifest) if err != nil { return nil, errors.Wrap(err, "cannot unmarshal manifest.json") } if len(manifest) == 0 { return nil, errors.New("manifest.json has no file mappings") } return manifest, nil }
go
func GetManifest(publicPath string) (map[string]string, error) { manifestPath := filepath.Join(publicPath, "assets", "manifest.json") contents, err := ioutil.ReadFile(manifestPath) if err != nil { return nil, err } if len(contents) == 0 { return nil, errors.New("manifest.json is empty") } manifest := map[string]string{} err = json.Unmarshal(contents, &manifest) if err != nil { return nil, errors.Wrap(err, "cannot unmarshal manifest.json") } if len(manifest) == 0 { return nil, errors.New("manifest.json has no file mappings") } return manifest, nil }
[ "func", "GetManifest", "(", "publicPath", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "manifestPath", ":=", "filepath", ".", "Join", "(", "publicPath", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "contents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "manifestPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "contents", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "manifest", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "contents", ",", "&", "manifest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "manifest", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "manifest", ",", "nil", "\n", "}" ]
// GetManifest reads the manifest.json file in the public assets folder // and returns a map of its mappings. Returns error if manifest.json not found.
[ "GetManifest", "reads", "the", "manifest", ".", "json", "file", "in", "the", "public", "assets", "folder", "and", "returns", "a", "map", "of", "its", "mappings", ".", "Returns", "error", "if", "manifest", ".", "json", "not", "found", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L67-L87
15,692
volatiletech/abcweb
abcrender/render.go
AppHelpers
func AppHelpers(manifest map[string]string) template.FuncMap { return template.FuncMap{ "liveReload": liveReloadHelper, "jsPath": func(relpath string) string { return manifestHelper("js", relpath, manifest) }, "cssPath": func(relpath string) string { return manifestHelper("css", relpath, manifest) }, "imgPath": func(relpath string) string { return manifestHelper("img", relpath, manifest) }, "videoPath": func(relpath string) string { return manifestHelper("video", relpath, manifest) }, "audioPath": func(relpath string) string { return manifestHelper("audio", relpath, manifest) }, "fontPath": func(relpath string) string { return manifestHelper("font", relpath, manifest) }, "assetPath": func(relpath string) string { v, ok := manifest[relpath] if !ok { return "/assets/" + relpath } return "/assets/" + v }, // wrap full asset paths in include tags "cssTag": cssTag, "jsTag": jsTag, "joinPath": func(pieces ...string) string { return strings.Join(pieces, "/") }, // return all javascript include tags for all twitter bootstrap js plugins // for the default bootstrap install. "jsBootstrap": jsBootstrap, } }
go
func AppHelpers(manifest map[string]string) template.FuncMap { return template.FuncMap{ "liveReload": liveReloadHelper, "jsPath": func(relpath string) string { return manifestHelper("js", relpath, manifest) }, "cssPath": func(relpath string) string { return manifestHelper("css", relpath, manifest) }, "imgPath": func(relpath string) string { return manifestHelper("img", relpath, manifest) }, "videoPath": func(relpath string) string { return manifestHelper("video", relpath, manifest) }, "audioPath": func(relpath string) string { return manifestHelper("audio", relpath, manifest) }, "fontPath": func(relpath string) string { return manifestHelper("font", relpath, manifest) }, "assetPath": func(relpath string) string { v, ok := manifest[relpath] if !ok { return "/assets/" + relpath } return "/assets/" + v }, // wrap full asset paths in include tags "cssTag": cssTag, "jsTag": jsTag, "joinPath": func(pieces ...string) string { return strings.Join(pieces, "/") }, // return all javascript include tags for all twitter bootstrap js plugins // for the default bootstrap install. "jsBootstrap": jsBootstrap, } }
[ "func", "AppHelpers", "(", "manifest", "map", "[", "string", "]", "string", ")", "template", ".", "FuncMap", "{", "return", "template", ".", "FuncMap", "{", "\"", "\"", ":", "liveReloadHelper", ",", "\"", "\"", ":", "func", "(", "relpath", "string", ")", "string", "{", "return", "manifestHelper", "(", "\"", "\"", ",", "relpath", ",", "manifest", ")", "}", ",", "\"", "\"", ":", "func", "(", "relpath", "string", ")", "string", "{", "return", "manifestHelper", "(", "\"", "\"", ",", "relpath", ",", "manifest", ")", "}", ",", "\"", "\"", ":", "func", "(", "relpath", "string", ")", "string", "{", "return", "manifestHelper", "(", "\"", "\"", ",", "relpath", ",", "manifest", ")", "}", ",", "\"", "\"", ":", "func", "(", "relpath", "string", ")", "string", "{", "return", "manifestHelper", "(", "\"", "\"", ",", "relpath", ",", "manifest", ")", "}", ",", "\"", "\"", ":", "func", "(", "relpath", "string", ")", "string", "{", "return", "manifestHelper", "(", "\"", "\"", ",", "relpath", ",", "manifest", ")", "}", ",", "\"", "\"", ":", "func", "(", "relpath", "string", ")", "string", "{", "return", "manifestHelper", "(", "\"", "\"", ",", "relpath", ",", "manifest", ")", "}", ",", "\"", "\"", ":", "func", "(", "relpath", "string", ")", "string", "{", "v", ",", "ok", ":=", "manifest", "[", "relpath", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", "+", "relpath", "\n", "}", "\n", "return", "\"", "\"", "+", "v", "\n", "}", ",", "// wrap full asset paths in include tags", "\"", "\"", ":", "cssTag", ",", "\"", "\"", ":", "jsTag", ",", "\"", "\"", ":", "func", "(", "pieces", "...", "string", ")", "string", "{", "return", "strings", ".", "Join", "(", "pieces", ",", "\"", "\"", ")", "}", ",", "// return all javascript include tags for all twitter bootstrap js plugins", "// for the default bootstrap install.", "\"", "\"", ":", "jsBootstrap", ",", "}", "\n", "}" ]
// AppHelpers takes in the assets manifest and returns a map of the template // helper functions.
[ "AppHelpers", "takes", "in", "the", "assets", "manifest", "and", "returns", "a", "map", "of", "the", "template", "helper", "functions", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L91-L118
15,693
volatiletech/abcweb
abcrender/render.go
liveReloadHelper
func liveReloadHelper(relpath string, host string) string { return fmt.Sprintf("/assets/js/%s?host=%s", relpath, host) }
go
func liveReloadHelper(relpath string, host string) string { return fmt.Sprintf("/assets/js/%s?host=%s", relpath, host) }
[ "func", "liveReloadHelper", "(", "relpath", "string", ",", "host", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "relpath", ",", "host", ")", "\n", "}" ]
// liveReloadHelper is a helper to include the livereload javascript file // and pass through a host queryparam so that it works properly.
[ "liveReloadHelper", "is", "a", "helper", "to", "include", "the", "livereload", "javascript", "file", "and", "pass", "through", "a", "host", "queryparam", "so", "that", "it", "works", "properly", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L130-L132
15,694
volatiletech/abcweb
abcrender/render.go
cssTag
func cssTag(relpath string) template.HTML { return template.HTML(fmt.Sprintf("<link href=\"%s\" rel=\"stylesheet\">", relpath)) }
go
func cssTag(relpath string) template.HTML { return template.HTML(fmt.Sprintf("<link href=\"%s\" rel=\"stylesheet\">", relpath)) }
[ "func", "cssTag", "(", "relpath", "string", ")", "template", ".", "HTML", "{", "return", "template", ".", "HTML", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "relpath", ")", ")", "\n", "}" ]
// cssTag wraps the asset path in a css link include tag
[ "cssTag", "wraps", "the", "asset", "path", "in", "a", "css", "link", "include", "tag" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L135-L137
15,695
volatiletech/abcweb
abcrender/render.go
jsTag
func jsTag(relpath string) template.HTML { return template.HTML(fmt.Sprintf("<script src=\"%s\"></script>", relpath)) }
go
func jsTag(relpath string) template.HTML { return template.HTML(fmt.Sprintf("<script src=\"%s\"></script>", relpath)) }
[ "func", "jsTag", "(", "relpath", "string", ")", "template", ".", "HTML", "{", "return", "template", ".", "HTML", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "relpath", ")", ")", "\n", "}" ]
// jsTag wraps the asset path in a javascript script include tag
[ "jsTag", "wraps", "the", "asset", "path", "in", "a", "javascript", "script", "include", "tag" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L140-L142
15,696
volatiletech/abcweb
abcrender/render.go
jsBootstrap
func jsBootstrap() template.HTML { files := []string{ "/assets/js/bootstrap/transition.js", "/assets/js/bootstrap/util.js", "/assets/js/bootstrap/alert.js", "/assets/js/bootstrap/button.js", "/assets/js/bootstrap/carousel.js", "/assets/js/bootstrap/collapse.js", "/assets/js/bootstrap/dropdown.js", "/assets/js/bootstrap/modal.js", "/assets/js/bootstrap/scrollspy.js", "/assets/js/bootstrap/tab.js", "/assets/js/bootstrap/tooltip.js", "/assets/js/bootstrap/popover.js", } buf := bytes.Buffer{} for _, file := range files { buf.WriteString(fmt.Sprintf("<script src=\"%s\"></script>\n", file)) } return template.HTML(buf.String()) }
go
func jsBootstrap() template.HTML { files := []string{ "/assets/js/bootstrap/transition.js", "/assets/js/bootstrap/util.js", "/assets/js/bootstrap/alert.js", "/assets/js/bootstrap/button.js", "/assets/js/bootstrap/carousel.js", "/assets/js/bootstrap/collapse.js", "/assets/js/bootstrap/dropdown.js", "/assets/js/bootstrap/modal.js", "/assets/js/bootstrap/scrollspy.js", "/assets/js/bootstrap/tab.js", "/assets/js/bootstrap/tooltip.js", "/assets/js/bootstrap/popover.js", } buf := bytes.Buffer{} for _, file := range files { buf.WriteString(fmt.Sprintf("<script src=\"%s\"></script>\n", file)) } return template.HTML(buf.String()) }
[ "func", "jsBootstrap", "(", ")", "template", ".", "HTML", "{", "files", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n\n", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\n", "\"", ",", "file", ")", ")", "\n", "}", "\n", "return", "template", ".", "HTML", "(", "buf", ".", "String", "(", ")", ")", "\n", "}" ]
// jsBootstrap returns all javascript include tags for all twitter bootstrap // js plugins for the default generated bootstrap install.
[ "jsBootstrap", "returns", "all", "javascript", "include", "tags", "for", "all", "twitter", "bootstrap", "js", "plugins", "for", "the", "default", "generated", "bootstrap", "install", "." ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcrender/render.go#L146-L167
15,697
volatiletech/abcweb
abcsessions/cookie_options.go
NewCookieOptions
func NewCookieOptions() CookieOptions { return CookieOptions{ Name: "id", Path: "/", MaxAge: 0, Secure: true, HTTPOnly: true, } }
go
func NewCookieOptions() CookieOptions { return CookieOptions{ Name: "id", Path: "/", MaxAge: 0, Secure: true, HTTPOnly: true, } }
[ "func", "NewCookieOptions", "(", ")", "CookieOptions", "{", "return", "CookieOptions", "{", "Name", ":", "\"", "\"", ",", "Path", ":", "\"", "\"", ",", "MaxAge", ":", "0", ",", "Secure", ":", "true", ",", "HTTPOnly", ":", "true", ",", "}", "\n", "}" ]
// NewCookieOptions gives healthy defaults for session cookies
[ "NewCookieOptions", "gives", "healthy", "defaults", "for", "session", "cookies" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_options.go#L27-L35
15,698
volatiletech/abcweb
abcsessions/cookie_options.go
deleteCookie
func (c CookieOptions) deleteCookie(w http.ResponseWriter) { cookie := &http.Cookie{ // If the browser refuses to delete it, set value to "" so subsequent // requests replace it when it does not point to a valid session id. Path: c.Path, Domain: c.Domain, Value: "", Name: c.Name, MaxAge: -1, Expires: time.Now().UTC().AddDate(-1, 0, 0), HttpOnly: c.HTTPOnly, Secure: c.Secure, } w.(cookieWriter).SetCookie(cookie) }
go
func (c CookieOptions) deleteCookie(w http.ResponseWriter) { cookie := &http.Cookie{ // If the browser refuses to delete it, set value to "" so subsequent // requests replace it when it does not point to a valid session id. Path: c.Path, Domain: c.Domain, Value: "", Name: c.Name, MaxAge: -1, Expires: time.Now().UTC().AddDate(-1, 0, 0), HttpOnly: c.HTTPOnly, Secure: c.Secure, } w.(cookieWriter).SetCookie(cookie) }
[ "func", "(", "c", "CookieOptions", ")", "deleteCookie", "(", "w", "http", ".", "ResponseWriter", ")", "{", "cookie", ":=", "&", "http", ".", "Cookie", "{", "// If the browser refuses to delete it, set value to \"\" so subsequent", "// requests replace it when it does not point to a valid session id.", "Path", ":", "c", ".", "Path", ",", "Domain", ":", "c", ".", "Domain", ",", "Value", ":", "\"", "\"", ",", "Name", ":", "c", ".", "Name", ",", "MaxAge", ":", "-", "1", ",", "Expires", ":", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "AddDate", "(", "-", "1", ",", "0", ",", "0", ")", ",", "HttpOnly", ":", "c", ".", "HTTPOnly", ",", "Secure", ":", "c", ".", "Secure", ",", "}", "\n\n", "w", ".", "(", "cookieWriter", ")", ".", "SetCookie", "(", "cookie", ")", "\n", "}" ]
// deleteCookie sets the cookie to a deleted value to force the client to delete
[ "deleteCookie", "sets", "the", "cookie", "to", "a", "deleted", "value", "to", "force", "the", "client", "to", "delete" ]
9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66
https://github.com/volatiletech/abcweb/blob/9e9ffe4fa86ed4e557dcc4b9d59ca5d3d91c6a66/abcsessions/cookie_options.go#L56-L71
15,699
nbari/violetear
trie.go
contains
func (t *Trie) contains(path, version string) (*Trie, bool) { for _, n := range t.Node { if n.path == path && n.version == version { return n, true } } return nil, false }
go
func (t *Trie) contains(path, version string) (*Trie, bool) { for _, n := range t.Node { if n.path == path && n.version == version { return n, true } } return nil, false }
[ "func", "(", "t", "*", "Trie", ")", "contains", "(", "path", ",", "version", "string", ")", "(", "*", "Trie", ",", "bool", ")", "{", "for", "_", ",", "n", ":=", "range", "t", ".", "Node", "{", "if", "n", ".", "path", "==", "path", "&&", "n", ".", "version", "==", "version", "{", "return", "n", ",", "true", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "false", "\n", "}" ]
// contains check if path exists on node
[ "contains", "check", "if", "path", "exists", "on", "node" ]
971f3729520176a408b28de36d6f283f13b8e6d3
https://github.com/nbari/violetear/blob/971f3729520176a408b28de36d6f283f13b8e6d3/trie.go#L27-L34