repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
vulcand/oxy
ratelimit/tokenlimiter.go
New
func New(next http.Handler, extract utils.SourceExtractor, defaultRates *RateSet, opts ...TokenLimiterOption) (*TokenLimiter, error) { if defaultRates == nil || len(defaultRates.m) == 0 { return nil, fmt.Errorf("provide default rates") } if extract == nil { return nil, fmt.Errorf("provide extract function") } tl := &TokenLimiter{ next: next, defaultRates: defaultRates, extract: extract, log: log.StandardLogger(), } for _, o := range opts { if err := o(tl); err != nil { return nil, err } } setDefaults(tl) bucketSets, err := ttlmap.NewMapWithProvider(tl.capacity, tl.clock) if err != nil { return nil, err } tl.bucketSets = bucketSets return tl, nil }
go
func New(next http.Handler, extract utils.SourceExtractor, defaultRates *RateSet, opts ...TokenLimiterOption) (*TokenLimiter, error) { if defaultRates == nil || len(defaultRates.m) == 0 { return nil, fmt.Errorf("provide default rates") } if extract == nil { return nil, fmt.Errorf("provide extract function") } tl := &TokenLimiter{ next: next, defaultRates: defaultRates, extract: extract, log: log.StandardLogger(), } for _, o := range opts { if err := o(tl); err != nil { return nil, err } } setDefaults(tl) bucketSets, err := ttlmap.NewMapWithProvider(tl.capacity, tl.clock) if err != nil { return nil, err } tl.bucketSets = bucketSets return tl, nil }
[ "func", "New", "(", "next", "http", ".", "Handler", ",", "extract", "utils", ".", "SourceExtractor", ",", "defaultRates", "*", "RateSet", ",", "opts", "...", "TokenLimiterOption", ")", "(", "*", "TokenLimiter", ",", "error", ")", "{", "if", "defaultRates", ...
// New constructs a `TokenLimiter` middleware instance.
[ "New", "constructs", "a", "TokenLimiter", "middleware", "instance", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/ratelimit/tokenlimiter.go#L80-L107
train
vulcand/oxy
ratelimit/tokenlimiter.go
ExtractRates
func ExtractRates(e RateExtractor) TokenLimiterOption { return func(cl *TokenLimiter) error { cl.extractRates = e return nil } }
go
func ExtractRates(e RateExtractor) TokenLimiterOption { return func(cl *TokenLimiter) error { cl.extractRates = e return nil } }
[ "func", "ExtractRates", "(", "e", "RateExtractor", ")", "TokenLimiterOption", "{", "return", "func", "(", "cl", "*", "TokenLimiter", ")", "error", "{", "cl", ".", "extractRates", "=", "e", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ExtractRates sets the rate extractor
[ "ExtractRates", "sets", "the", "rate", "extractor" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/ratelimit/tokenlimiter.go#L224-L229
train
vulcand/oxy
ratelimit/tokenlimiter.go
Clock
func Clock(clock timetools.TimeProvider) TokenLimiterOption { return func(cl *TokenLimiter) error { cl.clock = clock return nil } }
go
func Clock(clock timetools.TimeProvider) TokenLimiterOption { return func(cl *TokenLimiter) error { cl.clock = clock return nil } }
[ "func", "Clock", "(", "clock", "timetools", ".", "TimeProvider", ")", "TokenLimiterOption", "{", "return", "func", "(", "cl", "*", "TokenLimiter", ")", "error", "{", "cl", ".", "clock", "=", "clock", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Clock sets the clock
[ "Clock", "sets", "the", "clock" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/ratelimit/tokenlimiter.go#L232-L237
train
vulcand/oxy
ratelimit/tokenlimiter.go
Capacity
func Capacity(cap int) TokenLimiterOption { return func(cl *TokenLimiter) error { if cap <= 0 { return fmt.Errorf("bad capacity: %v", cap) } cl.capacity = cap return nil } }
go
func Capacity(cap int) TokenLimiterOption { return func(cl *TokenLimiter) error { if cap <= 0 { return fmt.Errorf("bad capacity: %v", cap) } cl.capacity = cap return nil } }
[ "func", "Capacity", "(", "cap", "int", ")", "TokenLimiterOption", "{", "return", "func", "(", "cl", "*", "TokenLimiter", ")", "error", "{", "if", "cap", "<=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cap", ")", "\n", "}", "\...
// Capacity sets the capacity
[ "Capacity", "sets", "the", "capacity" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/ratelimit/tokenlimiter.go#L240-L248
train
vulcand/oxy
buffer/buffer.go
MaxRequestBodyBytes
func MaxRequestBodyBytes(m int64) optSetter { return func(b *Buffer) error { if m < 0 { return fmt.Errorf("max bytes should be >= 0 got %d", m) } b.maxRequestBodyBytes = m return nil } }
go
func MaxRequestBodyBytes(m int64) optSetter { return func(b *Buffer) error { if m < 0 { return fmt.Errorf("max bytes should be >= 0 got %d", m) } b.maxRequestBodyBytes = m return nil } }
[ "func", "MaxRequestBodyBytes", "(", "m", "int64", ")", "optSetter", "{", "return", "func", "(", "b", "*", "Buffer", ")", "error", "{", "if", "m", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ")", "\n", "}", "\n", "b",...
// MaxRequestBodyBytes sets the maximum request body size in bytes
[ "MaxRequestBodyBytes", "sets", "the", "maximum", "request", "body", "size", "in", "bytes" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/buffer/buffer.go#L160-L168
train
vulcand/oxy
buffer/buffer.go
MemRequestBodyBytes
func MemRequestBodyBytes(m int64) optSetter { return func(b *Buffer) error { if m < 0 { return fmt.Errorf("mem bytes should be >= 0 got %d", m) } b.memRequestBodyBytes = m return nil } }
go
func MemRequestBodyBytes(m int64) optSetter { return func(b *Buffer) error { if m < 0 { return fmt.Errorf("mem bytes should be >= 0 got %d", m) } b.memRequestBodyBytes = m return nil } }
[ "func", "MemRequestBodyBytes", "(", "m", "int64", ")", "optSetter", "{", "return", "func", "(", "b", "*", "Buffer", ")", "error", "{", "if", "m", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ")", "\n", "}", "\n", "b",...
// MemRequestBodyBytes bytes sets the maximum request body to be stored in memory // buffer middleware will serialize the excess to disk.
[ "MemRequestBodyBytes", "bytes", "sets", "the", "maximum", "request", "body", "to", "be", "stored", "in", "memory", "buffer", "middleware", "will", "serialize", "the", "excess", "to", "disk", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/buffer/buffer.go#L172-L180
train
vulcand/oxy
buffer/buffer.go
MaxResponseBodyBytes
func MaxResponseBodyBytes(m int64) optSetter { return func(b *Buffer) error { if m < 0 { return fmt.Errorf("max bytes should be >= 0 got %d", m) } b.maxResponseBodyBytes = m return nil } }
go
func MaxResponseBodyBytes(m int64) optSetter { return func(b *Buffer) error { if m < 0 { return fmt.Errorf("max bytes should be >= 0 got %d", m) } b.maxResponseBodyBytes = m return nil } }
[ "func", "MaxResponseBodyBytes", "(", "m", "int64", ")", "optSetter", "{", "return", "func", "(", "b", "*", "Buffer", ")", "error", "{", "if", "m", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ")", "\n", "}", "\n", "b"...
// MaxResponseBodyBytes sets the maximum request body size in bytes
[ "MaxResponseBodyBytes", "sets", "the", "maximum", "request", "body", "size", "in", "bytes" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/buffer/buffer.go#L183-L191
train
vulcand/oxy
buffer/buffer.go
MemResponseBodyBytes
func MemResponseBodyBytes(m int64) optSetter { return func(b *Buffer) error { if m < 0 { return fmt.Errorf("mem bytes should be >= 0 got %d", m) } b.memResponseBodyBytes = m return nil } }
go
func MemResponseBodyBytes(m int64) optSetter { return func(b *Buffer) error { if m < 0 { return fmt.Errorf("mem bytes should be >= 0 got %d", m) } b.memResponseBodyBytes = m return nil } }
[ "func", "MemResponseBodyBytes", "(", "m", "int64", ")", "optSetter", "{", "return", "func", "(", "b", "*", "Buffer", ")", "error", "{", "if", "m", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ")", "\n", "}", "\n", "b"...
// MemResponseBodyBytes sets the maximum request body to be stored in memory // buffer middleware will serialize the excess to disk.
[ "MemResponseBodyBytes", "sets", "the", "maximum", "request", "body", "to", "be", "stored", "in", "memory", "buffer", "middleware", "will", "serialize", "the", "excess", "to", "disk", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/buffer/buffer.go#L195-L203
train
vulcand/oxy
buffer/buffer.go
Wrap
func (b *Buffer) Wrap(next http.Handler) error { b.next = next return nil }
go
func (b *Buffer) Wrap(next http.Handler) error { b.next = next return nil }
[ "func", "(", "b", "*", "Buffer", ")", "Wrap", "(", "next", "http", ".", "Handler", ")", "error", "{", "b", ".", "next", "=", "next", "\n", "return", "nil", "\n", "}" ]
// Wrap sets the next handler to be called by buffer handler.
[ "Wrap", "sets", "the", "next", "handler", "to", "be", "called", "by", "buffer", "handler", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/buffer/buffer.go#L206-L209
train
vulcand/oxy
buffer/buffer.go
CloseNotify
func (b *bufferWriter) CloseNotify() <-chan bool { if cn, ok := b.responseWriter.(http.CloseNotifier); ok { return cn.CloseNotify() } b.log.Warningf("Upstream ResponseWriter of type %v does not implement http.CloseNotifier. Returning dummy channel.", reflect.TypeOf(b.responseWriter)) return make(<-chan bool) }
go
func (b *bufferWriter) CloseNotify() <-chan bool { if cn, ok := b.responseWriter.(http.CloseNotifier); ok { return cn.CloseNotify() } b.log.Warningf("Upstream ResponseWriter of type %v does not implement http.CloseNotifier. Returning dummy channel.", reflect.TypeOf(b.responseWriter)) return make(<-chan bool) }
[ "func", "(", "b", "*", "bufferWriter", ")", "CloseNotify", "(", ")", "<-", "chan", "bool", "{", "if", "cn", ",", "ok", ":=", "b", ".", "responseWriter", ".", "(", "http", ".", "CloseNotifier", ")", ";", "ok", "{", "return", "cn", ".", "CloseNotify", ...
// CloseNotifier interface - this allows downstream connections to be terminated when the client terminates.
[ "CloseNotifier", "interface", "-", "this", "allows", "downstream", "connections", "to", "be", "terminated", "when", "the", "client", "terminates", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/buffer/buffer.go#L402-L408
train
vulcand/oxy
buffer/buffer.go
Hijack
func (b *bufferWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hi, ok := b.responseWriter.(http.Hijacker); ok { conn, rw, err := hi.Hijack() if err != nil { b.hijacked = true } return conn, rw, err } b.log.Warningf("Upstream ResponseWriter of type %v does not implement http.Hijacker. Returning dummy channel.", reflect.TypeOf(b.responseWriter)) return nil, nil, fmt.Errorf("the response writer wrapped in this proxy does not implement http.Hijacker. Its type is: %v", reflect.TypeOf(b.responseWriter)) }
go
func (b *bufferWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hi, ok := b.responseWriter.(http.Hijacker); ok { conn, rw, err := hi.Hijack() if err != nil { b.hijacked = true } return conn, rw, err } b.log.Warningf("Upstream ResponseWriter of type %v does not implement http.Hijacker. Returning dummy channel.", reflect.TypeOf(b.responseWriter)) return nil, nil, fmt.Errorf("the response writer wrapped in this proxy does not implement http.Hijacker. Its type is: %v", reflect.TypeOf(b.responseWriter)) }
[ "func", "(", "b", "*", "bufferWriter", ")", "Hijack", "(", ")", "(", "net", ".", "Conn", ",", "*", "bufio", ".", "ReadWriter", ",", "error", ")", "{", "if", "hi", ",", "ok", ":=", "b", ".", "responseWriter", ".", "(", "http", ".", "Hijacker", ")"...
// Hijack This allows connections to be hijacked for websockets for instance.
[ "Hijack", "This", "allows", "connections", "to", "be", "hijacked", "for", "websockets", "for", "instance", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/buffer/buffer.go#L411-L421
train
vulcand/oxy
memmetrics/roundtrip.go
RTCounter
func RTCounter(new NewCounterFn) rrOptSetter { return func(r *RTMetrics) error { r.newCounter = new return nil } }
go
func RTCounter(new NewCounterFn) rrOptSetter { return func(r *RTMetrics) error { r.newCounter = new return nil } }
[ "func", "RTCounter", "(", "new", "NewCounterFn", ")", "rrOptSetter", "{", "return", "func", "(", "r", "*", "RTMetrics", ")", "error", "{", "r", ".", "newCounter", "=", "new", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// RTCounter set a builder function for Counter
[ "RTCounter", "set", "a", "builder", "function", "for", "Counter" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L42-L47
train
vulcand/oxy
memmetrics/roundtrip.go
RTHistogram
func RTHistogram(fn NewRollingHistogramFn) rrOptSetter { return func(r *RTMetrics) error { r.newHist = fn return nil } }
go
func RTHistogram(fn NewRollingHistogramFn) rrOptSetter { return func(r *RTMetrics) error { r.newHist = fn return nil } }
[ "func", "RTHistogram", "(", "fn", "NewRollingHistogramFn", ")", "rrOptSetter", "{", "return", "func", "(", "r", "*", "RTMetrics", ")", "error", "{", "r", ".", "newHist", "=", "fn", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// RTHistogram set a builder function for RollingHistogram
[ "RTHistogram", "set", "a", "builder", "function", "for", "RollingHistogram" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L50-L55
train
vulcand/oxy
memmetrics/roundtrip.go
RTClock
func RTClock(clock timetools.TimeProvider) rrOptSetter { return func(r *RTMetrics) error { r.clock = clock return nil } }
go
func RTClock(clock timetools.TimeProvider) rrOptSetter { return func(r *RTMetrics) error { r.clock = clock return nil } }
[ "func", "RTClock", "(", "clock", "timetools", ".", "TimeProvider", ")", "rrOptSetter", "{", "return", "func", "(", "r", "*", "RTMetrics", ")", "error", "{", "r", ".", "clock", "=", "clock", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// RTClock sets a clock
[ "RTClock", "sets", "a", "clock" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L58-L63
train
vulcand/oxy
memmetrics/roundtrip.go
NewRTMetrics
func NewRTMetrics(settings ...rrOptSetter) (*RTMetrics, error) { m := &RTMetrics{ statusCodes: make(map[int]*RollingCounter), statusCodesLock: sync.RWMutex{}, } for _, s := range settings { if err := s(m); err != nil { return nil, err } } if m.clock == nil { m.clock = &timetools.RealTime{} } if m.newCounter == nil { m.newCounter = func() (*RollingCounter, error) { return NewCounter(counterBuckets, counterResolution, CounterClock(m.clock)) } } if m.newHist == nil { m.newHist = func() (*RollingHDRHistogram, error) { return NewRollingHDRHistogram(histMin, histMax, histSignificantFigures, histPeriod, histBuckets, RollingClock(m.clock)) } } h, err := m.newHist() if err != nil { return nil, err } netErrors, err := m.newCounter() if err != nil { return nil, err } total, err := m.newCounter() if err != nil { return nil, err } m.histogram = h m.netErrors = netErrors m.total = total return m, nil }
go
func NewRTMetrics(settings ...rrOptSetter) (*RTMetrics, error) { m := &RTMetrics{ statusCodes: make(map[int]*RollingCounter), statusCodesLock: sync.RWMutex{}, } for _, s := range settings { if err := s(m); err != nil { return nil, err } } if m.clock == nil { m.clock = &timetools.RealTime{} } if m.newCounter == nil { m.newCounter = func() (*RollingCounter, error) { return NewCounter(counterBuckets, counterResolution, CounterClock(m.clock)) } } if m.newHist == nil { m.newHist = func() (*RollingHDRHistogram, error) { return NewRollingHDRHistogram(histMin, histMax, histSignificantFigures, histPeriod, histBuckets, RollingClock(m.clock)) } } h, err := m.newHist() if err != nil { return nil, err } netErrors, err := m.newCounter() if err != nil { return nil, err } total, err := m.newCounter() if err != nil { return nil, err } m.histogram = h m.netErrors = netErrors m.total = total return m, nil }
[ "func", "NewRTMetrics", "(", "settings", "...", "rrOptSetter", ")", "(", "*", "RTMetrics", ",", "error", ")", "{", "m", ":=", "&", "RTMetrics", "{", "statusCodes", ":", "make", "(", "map", "[", "int", "]", "*", "RollingCounter", ")", ",", "statusCodesLoc...
// NewRTMetrics returns new instance of metrics collector.
[ "NewRTMetrics", "returns", "new", "instance", "of", "metrics", "collector", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L66-L112
train
vulcand/oxy
memmetrics/roundtrip.go
Export
func (m *RTMetrics) Export() *RTMetrics { m.statusCodesLock.RLock() defer m.statusCodesLock.RUnlock() m.histogramLock.RLock() defer m.histogramLock.RUnlock() export := &RTMetrics{} export.statusCodesLock = sync.RWMutex{} export.histogramLock = sync.RWMutex{} export.total = m.total.Clone() export.netErrors = m.netErrors.Clone() exportStatusCodes := map[int]*RollingCounter{} for code, rollingCounter := range m.statusCodes { exportStatusCodes[code] = rollingCounter.Clone() } export.statusCodes = exportStatusCodes if m.histogram != nil { export.histogram = m.histogram.Export() } export.newCounter = m.newCounter export.newHist = m.newHist export.clock = m.clock return export }
go
func (m *RTMetrics) Export() *RTMetrics { m.statusCodesLock.RLock() defer m.statusCodesLock.RUnlock() m.histogramLock.RLock() defer m.histogramLock.RUnlock() export := &RTMetrics{} export.statusCodesLock = sync.RWMutex{} export.histogramLock = sync.RWMutex{} export.total = m.total.Clone() export.netErrors = m.netErrors.Clone() exportStatusCodes := map[int]*RollingCounter{} for code, rollingCounter := range m.statusCodes { exportStatusCodes[code] = rollingCounter.Clone() } export.statusCodes = exportStatusCodes if m.histogram != nil { export.histogram = m.histogram.Export() } export.newCounter = m.newCounter export.newHist = m.newHist export.clock = m.clock return export }
[ "func", "(", "m", "*", "RTMetrics", ")", "Export", "(", ")", "*", "RTMetrics", "{", "m", ".", "statusCodesLock", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "statusCodesLock", ".", "RUnlock", "(", ")", "\n", "m", ".", "histogramLock", ".", "RLoc...
// Export Returns a new RTMetrics which is a copy of the current one
[ "Export", "Returns", "a", "new", "RTMetrics", "which", "is", "a", "copy", "of", "the", "current", "one" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L115-L139
train
vulcand/oxy
memmetrics/roundtrip.go
NetworkErrorRatio
func (m *RTMetrics) NetworkErrorRatio() float64 { if m.total.Count() == 0 { return 0 } return float64(m.netErrors.Count()) / float64(m.total.Count()) }
go
func (m *RTMetrics) NetworkErrorRatio() float64 { if m.total.Count() == 0 { return 0 } return float64(m.netErrors.Count()) / float64(m.total.Count()) }
[ "func", "(", "m", "*", "RTMetrics", ")", "NetworkErrorRatio", "(", ")", "float64", "{", "if", "m", ".", "total", ".", "Count", "(", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "float64", "(", "m", ".", "netErrors", ".", "Count", ...
// NetworkErrorRatio calculates the amont of network errors such as time outs and dropped connection // that occurred in the given time window compared to the total requests count.
[ "NetworkErrorRatio", "calculates", "the", "amont", "of", "network", "errors", "such", "as", "time", "outs", "and", "dropped", "connection", "that", "occurred", "in", "the", "given", "time", "window", "compared", "to", "the", "total", "requests", "count", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L148-L153
train
vulcand/oxy
memmetrics/roundtrip.go
Append
func (m *RTMetrics) Append(other *RTMetrics) error { if m == other { return errors.New("RTMetrics cannot append to self") } if err := m.total.Append(other.total); err != nil { return err } if err := m.netErrors.Append(other.netErrors); err != nil { return err } copied := other.Export() m.statusCodesLock.Lock() defer m.statusCodesLock.Unlock() m.histogramLock.Lock() defer m.histogramLock.Unlock() for code, c := range copied.statusCodes { o, ok := m.statusCodes[code] if ok { if err := o.Append(c); err != nil { return err } } else { m.statusCodes[code] = c.Clone() } } return m.histogram.Append(copied.histogram) }
go
func (m *RTMetrics) Append(other *RTMetrics) error { if m == other { return errors.New("RTMetrics cannot append to self") } if err := m.total.Append(other.total); err != nil { return err } if err := m.netErrors.Append(other.netErrors); err != nil { return err } copied := other.Export() m.statusCodesLock.Lock() defer m.statusCodesLock.Unlock() m.histogramLock.Lock() defer m.histogramLock.Unlock() for code, c := range copied.statusCodes { o, ok := m.statusCodes[code] if ok { if err := o.Append(c); err != nil { return err } } else { m.statusCodes[code] = c.Clone() } } return m.histogram.Append(copied.histogram) }
[ "func", "(", "m", "*", "RTMetrics", ")", "Append", "(", "other", "*", "RTMetrics", ")", "error", "{", "if", "m", "==", "other", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "m", ".", "total", ...
// Append append a metric
[ "Append", "append", "a", "metric" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L176-L207
train
vulcand/oxy
memmetrics/roundtrip.go
Record
func (m *RTMetrics) Record(code int, duration time.Duration) { m.total.Inc(1) if code == http.StatusGatewayTimeout || code == http.StatusBadGateway { m.netErrors.Inc(1) } m.recordStatusCode(code) m.recordLatency(duration) }
go
func (m *RTMetrics) Record(code int, duration time.Duration) { m.total.Inc(1) if code == http.StatusGatewayTimeout || code == http.StatusBadGateway { m.netErrors.Inc(1) } m.recordStatusCode(code) m.recordLatency(duration) }
[ "func", "(", "m", "*", "RTMetrics", ")", "Record", "(", "code", "int", ",", "duration", "time", ".", "Duration", ")", "{", "m", ".", "total", ".", "Inc", "(", "1", ")", "\n", "if", "code", "==", "http", ".", "StatusGatewayTimeout", "||", "code", "=...
// Record records a metric
[ "Record", "records", "a", "metric" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L210-L217
train
vulcand/oxy
memmetrics/roundtrip.go
StatusCodesCounts
func (m *RTMetrics) StatusCodesCounts() map[int]int64 { sc := make(map[int]int64) m.statusCodesLock.RLock() defer m.statusCodesLock.RUnlock() for k, v := range m.statusCodes { if v.Count() != 0 { sc[k] = v.Count() } } return sc }
go
func (m *RTMetrics) StatusCodesCounts() map[int]int64 { sc := make(map[int]int64) m.statusCodesLock.RLock() defer m.statusCodesLock.RUnlock() for k, v := range m.statusCodes { if v.Count() != 0 { sc[k] = v.Count() } } return sc }
[ "func", "(", "m", "*", "RTMetrics", ")", "StatusCodesCounts", "(", ")", "map", "[", "int", "]", "int64", "{", "sc", ":=", "make", "(", "map", "[", "int", "]", "int64", ")", "\n", "m", ".", "statusCodesLock", ".", "RLock", "(", ")", "\n", "defer", ...
// StatusCodesCounts returns map with counts of the response codes
[ "StatusCodesCounts", "returns", "map", "with", "counts", "of", "the", "response", "codes" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L230-L240
train
vulcand/oxy
memmetrics/roundtrip.go
LatencyHistogram
func (m *RTMetrics) LatencyHistogram() (*HDRHistogram, error) { m.histogramLock.Lock() defer m.histogramLock.Unlock() return m.histogram.Merged() }
go
func (m *RTMetrics) LatencyHistogram() (*HDRHistogram, error) { m.histogramLock.Lock() defer m.histogramLock.Unlock() return m.histogram.Merged() }
[ "func", "(", "m", "*", "RTMetrics", ")", "LatencyHistogram", "(", ")", "(", "*", "HDRHistogram", ",", "error", ")", "{", "m", ".", "histogramLock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "histogramLock", ".", "Unlock", "(", ")", "\n", "retur...
// LatencyHistogram computes and returns resulting histogram with latencies observed.
[ "LatencyHistogram", "computes", "and", "returns", "resulting", "histogram", "with", "latencies", "observed", "." ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L243-L247
train
vulcand/oxy
memmetrics/roundtrip.go
Reset
func (m *RTMetrics) Reset() { m.statusCodesLock.Lock() defer m.statusCodesLock.Unlock() m.histogramLock.Lock() defer m.histogramLock.Unlock() m.histogram.Reset() m.total.Reset() m.netErrors.Reset() m.statusCodes = make(map[int]*RollingCounter) }
go
func (m *RTMetrics) Reset() { m.statusCodesLock.Lock() defer m.statusCodesLock.Unlock() m.histogramLock.Lock() defer m.histogramLock.Unlock() m.histogram.Reset() m.total.Reset() m.netErrors.Reset() m.statusCodes = make(map[int]*RollingCounter) }
[ "func", "(", "m", "*", "RTMetrics", ")", "Reset", "(", ")", "{", "m", ".", "statusCodesLock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "statusCodesLock", ".", "Unlock", "(", ")", "\n", "m", ".", "histogramLock", ".", "Lock", "(", ")", "\n", ...
// Reset reset metrics
[ "Reset", "reset", "metrics" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/roundtrip.go#L250-L259
train
vulcand/oxy
utils/netutils.go
NewProxyWriterWithLogger
func NewProxyWriterWithLogger(w http.ResponseWriter, l *log.Logger) *ProxyWriter { return &ProxyWriter{ w: w, log: l, } }
go
func NewProxyWriterWithLogger(w http.ResponseWriter, l *log.Logger) *ProxyWriter { return &ProxyWriter{ w: w, log: l, } }
[ "func", "NewProxyWriterWithLogger", "(", "w", "http", ".", "ResponseWriter", ",", "l", "*", "log", ".", "Logger", ")", "*", "ProxyWriter", "{", "return", "&", "ProxyWriter", "{", "w", ":", "w", ",", "log", ":", "l", ",", "}", "\n", "}" ]
// NewProxyWriterWithLogger creates a new ProxyWriter
[ "NewProxyWriterWithLogger", "creates", "a", "new", "ProxyWriter" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L30-L35
train
vulcand/oxy
utils/netutils.go
StatusCode
func (p *ProxyWriter) StatusCode() int { if p.code == 0 { // per contract standard lib will set this to http.StatusOK if not set // by user, here we avoid the confusion by mirroring this logic return http.StatusOK } return p.code }
go
func (p *ProxyWriter) StatusCode() int { if p.code == 0 { // per contract standard lib will set this to http.StatusOK if not set // by user, here we avoid the confusion by mirroring this logic return http.StatusOK } return p.code }
[ "func", "(", "p", "*", "ProxyWriter", ")", "StatusCode", "(", ")", "int", "{", "if", "p", ".", "code", "==", "0", "{", "// per contract standard lib will set this to http.StatusOK if not set", "// by user, here we avoid the confusion by mirroring this logic", "return", "htt...
// StatusCode gets status code
[ "StatusCode", "gets", "status", "code" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L38-L45
train
vulcand/oxy
utils/netutils.go
WriteHeader
func (p *ProxyWriter) WriteHeader(code int) { p.code = code p.w.WriteHeader(code) }
go
func (p *ProxyWriter) WriteHeader(code int) { p.code = code p.w.WriteHeader(code) }
[ "func", "(", "p", "*", "ProxyWriter", ")", "WriteHeader", "(", "code", "int", ")", "{", "p", ".", "code", "=", "code", "\n", "p", ".", "w", ".", "WriteHeader", "(", "code", ")", "\n", "}" ]
// WriteHeader writes status code
[ "WriteHeader", "writes", "status", "code" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L63-L66
train
vulcand/oxy
utils/netutils.go
Flush
func (p *ProxyWriter) Flush() { if f, ok := p.w.(http.Flusher); ok { f.Flush() } }
go
func (p *ProxyWriter) Flush() { if f, ok := p.w.(http.Flusher); ok { f.Flush() } }
[ "func", "(", "p", "*", "ProxyWriter", ")", "Flush", "(", ")", "{", "if", "f", ",", "ok", ":=", "p", ".", "w", ".", "(", "http", ".", "Flusher", ")", ";", "ok", "{", "f", ".", "Flush", "(", ")", "\n", "}", "\n", "}" ]
// Flush flush the writer
[ "Flush", "flush", "the", "writer" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L69-L73
train
vulcand/oxy
utils/netutils.go
NewBufferWriter
func NewBufferWriter(w io.WriteCloser) *BufferWriter { return &BufferWriter{ W: w, H: make(http.Header), } }
go
func NewBufferWriter(w io.WriteCloser) *BufferWriter { return &BufferWriter{ W: w, H: make(http.Header), } }
[ "func", "NewBufferWriter", "(", "w", "io", ".", "WriteCloser", ")", "*", "BufferWriter", "{", "return", "&", "BufferWriter", "{", "W", ":", "w", ",", "H", ":", "make", "(", "http", ".", "Header", ")", ",", "}", "\n", "}" ]
// NewBufferWriter creates a new BufferWriter
[ "NewBufferWriter", "creates", "a", "new", "BufferWriter" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L95-L100
train
vulcand/oxy
utils/netutils.go
CopyURL
func CopyURL(i *url.URL) *url.URL { out := *i if i.User != nil { out.User = &(*i.User) } return &out }
go
func CopyURL(i *url.URL) *url.URL { out := *i if i.User != nil { out.User = &(*i.User) } return &out }
[ "func", "CopyURL", "(", "i", "*", "url", ".", "URL", ")", "*", "url", ".", "URL", "{", "out", ":=", "*", "i", "\n", "if", "i", ".", "User", "!=", "nil", "{", "out", ".", "User", "=", "&", "(", "*", "i", ".", "User", ")", "\n", "}", "\n", ...
// CopyURL provides update safe copy by avoiding shallow copying User field
[ "CopyURL", "provides", "update", "safe", "copy", "by", "avoiding", "shallow", "copying", "User", "field" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L160-L166
train
vulcand/oxy
utils/netutils.go
CopyHeaders
func CopyHeaders(dst http.Header, src http.Header) { for k, vv := range src { dst[k] = append(dst[k], vv...) } }
go
func CopyHeaders(dst http.Header, src http.Header) { for k, vv := range src { dst[k] = append(dst[k], vv...) } }
[ "func", "CopyHeaders", "(", "dst", "http", ".", "Header", ",", "src", "http", ".", "Header", ")", "{", "for", "k", ",", "vv", ":=", "range", "src", "{", "dst", "[", "k", "]", "=", "append", "(", "dst", "[", "k", "]", ",", "vv", "...", ")", "\...
// CopyHeaders copies http headers from source to destination, it // does not overide, but adds multiple headers
[ "CopyHeaders", "copies", "http", "headers", "from", "source", "to", "destination", "it", "does", "not", "overide", "but", "adds", "multiple", "headers" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L170-L174
train
vulcand/oxy
utils/netutils.go
HasHeaders
func HasHeaders(names []string, headers http.Header) bool { for _, h := range names { if headers.Get(h) != "" { return true } } return false }
go
func HasHeaders(names []string, headers http.Header) bool { for _, h := range names { if headers.Get(h) != "" { return true } } return false }
[ "func", "HasHeaders", "(", "names", "[", "]", "string", ",", "headers", "http", ".", "Header", ")", "bool", "{", "for", "_", ",", "h", ":=", "range", "names", "{", "if", "headers", ".", "Get", "(", "h", ")", "!=", "\"", "\"", "{", "return", "true...
// HasHeaders determines whether any of the header names is present in the http headers
[ "HasHeaders", "determines", "whether", "any", "of", "the", "header", "names", "is", "present", "in", "the", "http", "headers" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/utils/netutils.go#L177-L184
train
vulcand/oxy
cbreaker/effect.go
NewWebhookSideEffectsWithLogger
func NewWebhookSideEffectsWithLogger(w Webhook, l *log.Logger) (*WebhookSideEffect, error) { if w.Method == "" { return nil, fmt.Errorf("Supply method") } _, err := url.Parse(w.URL) if err != nil { return nil, err } return &WebhookSideEffect{w: w, log: l}, nil }
go
func NewWebhookSideEffectsWithLogger(w Webhook, l *log.Logger) (*WebhookSideEffect, error) { if w.Method == "" { return nil, fmt.Errorf("Supply method") } _, err := url.Parse(w.URL) if err != nil { return nil, err } return &WebhookSideEffect{w: w, log: l}, nil }
[ "func", "NewWebhookSideEffectsWithLogger", "(", "w", "Webhook", ",", "l", "*", "log", ".", "Logger", ")", "(", "*", "WebhookSideEffect", ",", "error", ")", "{", "if", "w", ".", "Method", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf"...
// NewWebhookSideEffectsWithLogger creates a new WebhookSideEffect
[ "NewWebhookSideEffectsWithLogger", "creates", "a", "new", "WebhookSideEffect" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/effect.go#L38-L48
train
vulcand/oxy
cbreaker/effect.go
Exec
func (w *WebhookSideEffect) Exec() error { r, err := http.NewRequest(w.w.Method, w.w.URL, w.getBody()) if err != nil { return err } if len(w.w.Headers) != 0 { utils.CopyHeaders(r.Header, w.w.Headers) } if len(w.w.Form) != 0 { r.Header.Set("Content-Type", "application/x-www-form-urlencoded") } re, err := http.DefaultClient.Do(r) if err != nil { return err } if re.Body != nil { defer re.Body.Close() } body, err := ioutil.ReadAll(re.Body) if err != nil { return err } w.log.Debugf("%v got response: (%s): %s", w, re.Status, string(body)) return nil }
go
func (w *WebhookSideEffect) Exec() error { r, err := http.NewRequest(w.w.Method, w.w.URL, w.getBody()) if err != nil { return err } if len(w.w.Headers) != 0 { utils.CopyHeaders(r.Header, w.w.Headers) } if len(w.w.Form) != 0 { r.Header.Set("Content-Type", "application/x-www-form-urlencoded") } re, err := http.DefaultClient.Do(r) if err != nil { return err } if re.Body != nil { defer re.Body.Close() } body, err := ioutil.ReadAll(re.Body) if err != nil { return err } w.log.Debugf("%v got response: (%s): %s", w, re.Status, string(body)) return nil }
[ "func", "(", "w", "*", "WebhookSideEffect", ")", "Exec", "(", ")", "error", "{", "r", ",", "err", ":=", "http", ".", "NewRequest", "(", "w", ".", "w", ".", "Method", ",", "w", ".", "w", ".", "URL", ",", "w", ".", "getBody", "(", ")", ")", "\n...
// Exec execute the side effect
[ "Exec", "execute", "the", "side", "effect" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/effect.go#L66-L90
train
vulcand/oxy
memmetrics/counter.go
CounterClock
func CounterClock(c timetools.TimeProvider) rcOptSetter { return func(r *RollingCounter) error { r.clock = c return nil } }
go
func CounterClock(c timetools.TimeProvider) rcOptSetter { return func(r *RollingCounter) error { r.clock = c return nil } }
[ "func", "CounterClock", "(", "c", "timetools", ".", "TimeProvider", ")", "rcOptSetter", "{", "return", "func", "(", "r", "*", "RollingCounter", ")", "error", "{", "r", ".", "clock", "=", "c", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// CounterClock defines a counter clock
[ "CounterClock", "defines", "a", "counter", "clock" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L13-L18
train
vulcand/oxy
memmetrics/counter.go
NewCounter
func NewCounter(buckets int, resolution time.Duration, options ...rcOptSetter) (*RollingCounter, error) { if buckets <= 0 { return nil, fmt.Errorf("Buckets should be >= 0") } if resolution < time.Second { return nil, fmt.Errorf("Resolution should be larger than a second") } rc := &RollingCounter{ lastBucket: -1, resolution: resolution, values: make([]int, buckets), } for _, o := range options { if err := o(rc); err != nil { return nil, err } } if rc.clock == nil { rc.clock = &timetools.RealTime{} } return rc, nil }
go
func NewCounter(buckets int, resolution time.Duration, options ...rcOptSetter) (*RollingCounter, error) { if buckets <= 0 { return nil, fmt.Errorf("Buckets should be >= 0") } if resolution < time.Second { return nil, fmt.Errorf("Resolution should be larger than a second") } rc := &RollingCounter{ lastBucket: -1, resolution: resolution, values: make([]int, buckets), } for _, o := range options { if err := o(rc); err != nil { return nil, err } } if rc.clock == nil { rc.clock = &timetools.RealTime{} } return rc, nil }
[ "func", "NewCounter", "(", "buckets", "int", ",", "resolution", "time", ".", "Duration", ",", "options", "...", "rcOptSetter", ")", "(", "*", "RollingCounter", ",", "error", ")", "{", "if", "buckets", "<=", "0", "{", "return", "nil", ",", "fmt", ".", "...
// NewCounter creates a counter with fixed amount of buckets that are rotated every resolution period. // E.g. 10 buckets with 1 second means that every new second the bucket is refreshed, so it maintains 10 second rolling window. // By default creates a bucket with 10 buckets and 1 second resolution
[ "NewCounter", "creates", "a", "counter", "with", "fixed", "amount", "of", "buckets", "that", "are", "rotated", "every", "resolution", "period", ".", "E", ".", "g", ".", "10", "buckets", "with", "1", "second", "means", "that", "every", "new", "second", "the...
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L33-L59
train
vulcand/oxy
memmetrics/counter.go
Append
func (c *RollingCounter) Append(o *RollingCounter) error { c.Inc(int(o.Count())) return nil }
go
func (c *RollingCounter) Append(o *RollingCounter) error { c.Inc(int(o.Count())) return nil }
[ "func", "(", "c", "*", "RollingCounter", ")", "Append", "(", "o", "*", "RollingCounter", ")", "error", "{", "c", ".", "Inc", "(", "int", "(", "o", ".", "Count", "(", ")", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Append append a counter
[ "Append", "append", "a", "counter" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L62-L65
train
vulcand/oxy
memmetrics/counter.go
Clone
func (c *RollingCounter) Clone() *RollingCounter { c.cleanup() other := &RollingCounter{ resolution: c.resolution, values: make([]int, len(c.values)), clock: c.clock, lastBucket: c.lastBucket, lastUpdated: c.lastUpdated, } copy(other.values, c.values) return other }
go
func (c *RollingCounter) Clone() *RollingCounter { c.cleanup() other := &RollingCounter{ resolution: c.resolution, values: make([]int, len(c.values)), clock: c.clock, lastBucket: c.lastBucket, lastUpdated: c.lastUpdated, } copy(other.values, c.values) return other }
[ "func", "(", "c", "*", "RollingCounter", ")", "Clone", "(", ")", "*", "RollingCounter", "{", "c", ".", "cleanup", "(", ")", "\n", "other", ":=", "&", "RollingCounter", "{", "resolution", ":", "c", ".", "resolution", ",", "values", ":", "make", "(", "...
// Clone clone a counter
[ "Clone", "clone", "a", "counter" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L68-L79
train
vulcand/oxy
memmetrics/counter.go
Reset
func (c *RollingCounter) Reset() { c.lastBucket = -1 c.countedBuckets = 0 c.lastUpdated = time.Time{} for i := range c.values { c.values[i] = 0 } }
go
func (c *RollingCounter) Reset() { c.lastBucket = -1 c.countedBuckets = 0 c.lastUpdated = time.Time{} for i := range c.values { c.values[i] = 0 } }
[ "func", "(", "c", "*", "RollingCounter", ")", "Reset", "(", ")", "{", "c", ".", "lastBucket", "=", "-", "1", "\n", "c", ".", "countedBuckets", "=", "0", "\n", "c", ".", "lastUpdated", "=", "time", ".", "Time", "{", "}", "\n", "for", "i", ":=", ...
// Reset reset a counter
[ "Reset", "reset", "a", "counter" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L82-L89
train
vulcand/oxy
memmetrics/counter.go
WindowSize
func (c *RollingCounter) WindowSize() time.Duration { return time.Duration(len(c.values)) * c.resolution }
go
func (c *RollingCounter) WindowSize() time.Duration { return time.Duration(len(c.values)) * c.resolution }
[ "func", "(", "c", "*", "RollingCounter", ")", "WindowSize", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "len", "(", "c", ".", "values", ")", ")", "*", "c", ".", "resolution", "\n", "}" ]
// WindowSize gets windows size
[ "WindowSize", "gets", "windows", "size" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L113-L115
train
vulcand/oxy
memmetrics/counter.go
Inc
func (c *RollingCounter) Inc(v int) { c.cleanup() c.incBucketValue(v) }
go
func (c *RollingCounter) Inc(v int) { c.cleanup() c.incBucketValue(v) }
[ "func", "(", "c", "*", "RollingCounter", ")", "Inc", "(", "v", "int", ")", "{", "c", ".", "cleanup", "(", ")", "\n", "c", ".", "incBucketValue", "(", "v", ")", "\n", "}" ]
// Inc increment counter
[ "Inc", "increment", "counter" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L118-L121
train
vulcand/oxy
memmetrics/counter.go
getBucket
func (c *RollingCounter) getBucket(t time.Time) int { return int(t.Truncate(c.resolution).Unix() % int64(len(c.values))) }
go
func (c *RollingCounter) getBucket(t time.Time) int { return int(t.Truncate(c.resolution).Unix() % int64(len(c.values))) }
[ "func", "(", "c", "*", "RollingCounter", ")", "getBucket", "(", "t", "time", ".", "Time", ")", "int", "{", "return", "int", "(", "t", ".", "Truncate", "(", "c", ".", "resolution", ")", ".", "Unix", "(", ")", "%", "int64", "(", "len", "(", "c", ...
// Returns the number in the moving window bucket that this slot occupies
[ "Returns", "the", "number", "in", "the", "moving", "window", "bucket", "that", "this", "slot", "occupies" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L140-L142
train
vulcand/oxy
memmetrics/counter.go
cleanup
func (c *RollingCounter) cleanup() { now := c.clock.UtcNow() for i := 0; i < len(c.values); i++ { now = now.Add(time.Duration(-1*i) * c.resolution) if now.Truncate(c.resolution).After(c.lastUpdated.Truncate(c.resolution)) { c.values[c.getBucket(now)] = 0 } else { break } } }
go
func (c *RollingCounter) cleanup() { now := c.clock.UtcNow() for i := 0; i < len(c.values); i++ { now = now.Add(time.Duration(-1*i) * c.resolution) if now.Truncate(c.resolution).After(c.lastUpdated.Truncate(c.resolution)) { c.values[c.getBucket(now)] = 0 } else { break } } }
[ "func", "(", "c", "*", "RollingCounter", ")", "cleanup", "(", ")", "{", "now", ":=", "c", ".", "clock", ".", "UtcNow", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "c", ".", "values", ")", ";", "i", "++", "{", "now", "=...
// Reset buckets that were not updated
[ "Reset", "buckets", "that", "were", "not", "updated" ]
c34b0c501e43223bc816ac9b40b0ac29c44c8952
https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/counter.go#L145-L155
train
rs/xid
id.go
readMachineID
func readMachineID() []byte { id := make([]byte, 3) hid, err := readPlatformMachineID() if err != nil || len(hid) == 0 { hid, err = os.Hostname() } if err == nil && len(hid) != 0 { hw := md5.New() hw.Write([]byte(hid)) copy(id, hw.Sum(nil)) } else { // Fallback to rand number if machine id can't be gathered if _, randErr := rand.Reader.Read(id); randErr != nil { panic(fmt.Errorf("xid: cannot get hostname nor generate a random number: %v; %v", err, randErr)) } } return id }
go
func readMachineID() []byte { id := make([]byte, 3) hid, err := readPlatformMachineID() if err != nil || len(hid) == 0 { hid, err = os.Hostname() } if err == nil && len(hid) != 0 { hw := md5.New() hw.Write([]byte(hid)) copy(id, hw.Sum(nil)) } else { // Fallback to rand number if machine id can't be gathered if _, randErr := rand.Reader.Read(id); randErr != nil { panic(fmt.Errorf("xid: cannot get hostname nor generate a random number: %v; %v", err, randErr)) } } return id }
[ "func", "readMachineID", "(", ")", "[", "]", "byte", "{", "id", ":=", "make", "(", "[", "]", "byte", ",", "3", ")", "\n", "hid", ",", "err", ":=", "readPlatformMachineID", "(", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "hid", ")", ...
// readMachineId generates machine id and puts it into the machineId global // variable. If this function fails to get the hostname, it will cause // a runtime error.
[ "readMachineId", "generates", "machine", "id", "and", "puts", "it", "into", "the", "machineId", "global", "variable", ".", "If", "this", "function", "fails", "to", "get", "the", "hostname", "it", "will", "cause", "a", "runtime", "error", "." ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L117-L134
train
rs/xid
id.go
randInt
func randInt() uint32 { b := make([]byte, 3) if _, err := rand.Reader.Read(b); err != nil { panic(fmt.Errorf("xid: cannot generate random number: %v;", err)) } return uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2]) }
go
func randInt() uint32 { b := make([]byte, 3) if _, err := rand.Reader.Read(b); err != nil { panic(fmt.Errorf("xid: cannot generate random number: %v;", err)) } return uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2]) }
[ "func", "randInt", "(", ")", "uint32", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "3", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Reader", ".", "Read", "(", "b", ")", ";", "err", "!=", "nil", "{", "panic", "(", "fmt", "....
// randInt generates a random uint32
[ "randInt", "generates", "a", "random", "uint32" ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L137-L143
train
rs/xid
id.go
NewWithTime
func NewWithTime(t time.Time) ID { var id ID // Timestamp, 4 bytes, big endian binary.BigEndian.PutUint32(id[:], uint32(t.Unix())) // Machine, first 3 bytes of md5(hostname) id[4] = machineID[0] id[5] = machineID[1] id[6] = machineID[2] // Pid, 2 bytes, specs don't specify endianness, but we use big endian. id[7] = byte(pid >> 8) id[8] = byte(pid) // Increment, 3 bytes, big endian i := atomic.AddUint32(&objectIDCounter, 1) id[9] = byte(i >> 16) id[10] = byte(i >> 8) id[11] = byte(i) return id }
go
func NewWithTime(t time.Time) ID { var id ID // Timestamp, 4 bytes, big endian binary.BigEndian.PutUint32(id[:], uint32(t.Unix())) // Machine, first 3 bytes of md5(hostname) id[4] = machineID[0] id[5] = machineID[1] id[6] = machineID[2] // Pid, 2 bytes, specs don't specify endianness, but we use big endian. id[7] = byte(pid >> 8) id[8] = byte(pid) // Increment, 3 bytes, big endian i := atomic.AddUint32(&objectIDCounter, 1) id[9] = byte(i >> 16) id[10] = byte(i >> 8) id[11] = byte(i) return id }
[ "func", "NewWithTime", "(", "t", "time", ".", "Time", ")", "ID", "{", "var", "id", "ID", "\n", "// Timestamp, 4 bytes, big endian", "binary", ".", "BigEndian", ".", "PutUint32", "(", "id", "[", ":", "]", ",", "uint32", "(", "t", ".", "Unix", "(", ")", ...
// NewWithTime generates a globally unique ID with the passed in time
[ "NewWithTime", "generates", "a", "globally", "unique", "ID", "with", "the", "passed", "in", "time" ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L151-L168
train
rs/xid
id.go
FromString
func FromString(id string) (ID, error) { i := &ID{} err := i.UnmarshalText([]byte(id)) return *i, err }
go
func FromString(id string) (ID, error) { i := &ID{} err := i.UnmarshalText([]byte(id)) return *i, err }
[ "func", "FromString", "(", "id", "string", ")", "(", "ID", ",", "error", ")", "{", "i", ":=", "&", "ID", "{", "}", "\n", "err", ":=", "i", ".", "UnmarshalText", "(", "[", "]", "byte", "(", "id", ")", ")", "\n", "return", "*", "i", ",", "err",...
// FromString reads an ID from its string representation
[ "FromString", "reads", "an", "ID", "from", "its", "string", "representation" ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L171-L175
train
rs/xid
id.go
encode
func encode(dst, id []byte) { _ = dst[19] _ = id[11] dst[19] = encoding[(id[11]<<4)&0x1F] dst[18] = encoding[(id[11]>>1)&0x1F] dst[17] = encoding[(id[11]>>6)&0x1F|(id[10]<<2)&0x1F] dst[16] = encoding[id[10]>>3] dst[15] = encoding[id[9]&0x1F] dst[14] = encoding[(id[9]>>5)|(id[8]<<3)&0x1F] dst[13] = encoding[(id[8]>>2)&0x1F] dst[12] = encoding[id[8]>>7|(id[7]<<1)&0x1F] dst[11] = encoding[(id[7]>>4)&0x1F|(id[6]<<4)&0x1F] dst[10] = encoding[(id[6]>>1)&0x1F] dst[9] = encoding[(id[6]>>6)&0x1F|(id[5]<<2)&0x1F] dst[8] = encoding[id[5]>>3] dst[7] = encoding[id[4]&0x1F] dst[6] = encoding[id[4]>>5|(id[3]<<3)&0x1F] dst[5] = encoding[(id[3]>>2)&0x1F] dst[4] = encoding[id[3]>>7|(id[2]<<1)&0x1F] dst[3] = encoding[(id[2]>>4)&0x1F|(id[1]<<4)&0x1F] dst[2] = encoding[(id[1]>>1)&0x1F] dst[1] = encoding[(id[1]>>6)&0x1F|(id[0]<<2)&0x1F] dst[0] = encoding[id[0]>>3] }
go
func encode(dst, id []byte) { _ = dst[19] _ = id[11] dst[19] = encoding[(id[11]<<4)&0x1F] dst[18] = encoding[(id[11]>>1)&0x1F] dst[17] = encoding[(id[11]>>6)&0x1F|(id[10]<<2)&0x1F] dst[16] = encoding[id[10]>>3] dst[15] = encoding[id[9]&0x1F] dst[14] = encoding[(id[9]>>5)|(id[8]<<3)&0x1F] dst[13] = encoding[(id[8]>>2)&0x1F] dst[12] = encoding[id[8]>>7|(id[7]<<1)&0x1F] dst[11] = encoding[(id[7]>>4)&0x1F|(id[6]<<4)&0x1F] dst[10] = encoding[(id[6]>>1)&0x1F] dst[9] = encoding[(id[6]>>6)&0x1F|(id[5]<<2)&0x1F] dst[8] = encoding[id[5]>>3] dst[7] = encoding[id[4]&0x1F] dst[6] = encoding[id[4]>>5|(id[3]<<3)&0x1F] dst[5] = encoding[(id[3]>>2)&0x1F] dst[4] = encoding[id[3]>>7|(id[2]<<1)&0x1F] dst[3] = encoding[(id[2]>>4)&0x1F|(id[1]<<4)&0x1F] dst[2] = encoding[(id[1]>>1)&0x1F] dst[1] = encoding[(id[1]>>6)&0x1F|(id[0]<<2)&0x1F] dst[0] = encoding[id[0]>>3] }
[ "func", "encode", "(", "dst", ",", "id", "[", "]", "byte", ")", "{", "_", "=", "dst", "[", "19", "]", "\n", "_", "=", "id", "[", "11", "]", "\n\n", "dst", "[", "19", "]", "=", "encoding", "[", "(", "id", "[", "11", "]", "<<", "4", ")", ...
// encode by unrolling the stdlib base32 algorithm + removing all safe checks
[ "encode", "by", "unrolling", "the", "stdlib", "base32", "algorithm", "+", "removing", "all", "safe", "checks" ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L203-L227
train
rs/xid
id.go
decode
func decode(id *ID, src []byte) { _ = src[19] _ = id[11] id[11] = dec[src[17]]<<6 | dec[src[18]]<<1 | dec[src[19]]>>4 id[10] = dec[src[16]]<<3 | dec[src[17]]>>2 id[9] = dec[src[14]]<<5 | dec[src[15]] id[8] = dec[src[12]]<<7 | dec[src[13]]<<2 | dec[src[14]]>>3 id[7] = dec[src[11]]<<4 | dec[src[12]]>>1 id[6] = dec[src[9]]<<6 | dec[src[10]]<<1 | dec[src[11]]>>4 id[5] = dec[src[8]]<<3 | dec[src[9]]>>2 id[4] = dec[src[6]]<<5 | dec[src[7]] id[3] = dec[src[4]]<<7 | dec[src[5]]<<2 | dec[src[6]]>>3 id[2] = dec[src[3]]<<4 | dec[src[4]]>>1 id[1] = dec[src[1]]<<6 | dec[src[2]]<<1 | dec[src[3]]>>4 id[0] = dec[src[0]]<<3 | dec[src[1]]>>2 }
go
func decode(id *ID, src []byte) { _ = src[19] _ = id[11] id[11] = dec[src[17]]<<6 | dec[src[18]]<<1 | dec[src[19]]>>4 id[10] = dec[src[16]]<<3 | dec[src[17]]>>2 id[9] = dec[src[14]]<<5 | dec[src[15]] id[8] = dec[src[12]]<<7 | dec[src[13]]<<2 | dec[src[14]]>>3 id[7] = dec[src[11]]<<4 | dec[src[12]]>>1 id[6] = dec[src[9]]<<6 | dec[src[10]]<<1 | dec[src[11]]>>4 id[5] = dec[src[8]]<<3 | dec[src[9]]>>2 id[4] = dec[src[6]]<<5 | dec[src[7]] id[3] = dec[src[4]]<<7 | dec[src[5]]<<2 | dec[src[6]]>>3 id[2] = dec[src[3]]<<4 | dec[src[4]]>>1 id[1] = dec[src[1]]<<6 | dec[src[2]]<<1 | dec[src[3]]>>4 id[0] = dec[src[0]]<<3 | dec[src[1]]>>2 }
[ "func", "decode", "(", "id", "*", "ID", ",", "src", "[", "]", "byte", ")", "{", "_", "=", "src", "[", "19", "]", "\n", "_", "=", "id", "[", "11", "]", "\n\n", "id", "[", "11", "]", "=", "dec", "[", "src", "[", "17", "]", "]", "<<", "6",...
// decode by unrolling the stdlib base32 algorithm + removing all safe checks
[ "decode", "by", "unrolling", "the", "stdlib", "base32", "algorithm", "+", "removing", "all", "safe", "checks" ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L254-L270
train
rs/xid
id.go
Time
func (id ID) Time() time.Time { // First 4 bytes of ObjectId is 32-bit big-endian seconds from epoch. secs := int64(binary.BigEndian.Uint32(id[0:4])) return time.Unix(secs, 0) }
go
func (id ID) Time() time.Time { // First 4 bytes of ObjectId is 32-bit big-endian seconds from epoch. secs := int64(binary.BigEndian.Uint32(id[0:4])) return time.Unix(secs, 0) }
[ "func", "(", "id", "ID", ")", "Time", "(", ")", "time", ".", "Time", "{", "// First 4 bytes of ObjectId is 32-bit big-endian seconds from epoch.", "secs", ":=", "int64", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "id", "[", "0", ":", "4", "]", ")",...
// Time returns the timestamp part of the id. // It's a runtime error to call this method with an invalid id.
[ "Time", "returns", "the", "timestamp", "part", "of", "the", "id", ".", "It", "s", "a", "runtime", "error", "to", "call", "this", "method", "with", "an", "invalid", "id", "." ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L274-L278
train
rs/xid
id.go
Counter
func (id ID) Counter() int32 { b := id[9:12] // Counter is stored as big-endian 3-byte value return int32(uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2])) }
go
func (id ID) Counter() int32 { b := id[9:12] // Counter is stored as big-endian 3-byte value return int32(uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2])) }
[ "func", "(", "id", "ID", ")", "Counter", "(", ")", "int32", "{", "b", ":=", "id", "[", "9", ":", "12", "]", "\n", "// Counter is stored as big-endian 3-byte value", "return", "int32", "(", "uint32", "(", "b", "[", "0", "]", ")", "<<", "16", "|", "uin...
// Counter returns the incrementing value part of the id. // It's a runtime error to call this method with an invalid id.
[ "Counter", "returns", "the", "incrementing", "value", "part", "of", "the", "id", ".", "It", "s", "a", "runtime", "error", "to", "call", "this", "method", "with", "an", "invalid", "id", "." ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L294-L298
train
rs/xid
id.go
FromBytes
func FromBytes(b []byte) (ID, error) { var id ID if len(b) != rawLen { return id, ErrInvalidID } copy(id[:], b) return id, nil }
go
func FromBytes(b []byte) (ID, error) { var id ID if len(b) != rawLen { return id, ErrInvalidID } copy(id[:], b) return id, nil }
[ "func", "FromBytes", "(", "b", "[", "]", "byte", ")", "(", "ID", ",", "error", ")", "{", "var", "id", "ID", "\n", "if", "len", "(", "b", ")", "!=", "rawLen", "{", "return", "id", ",", "ErrInvalidID", "\n", "}", "\n", "copy", "(", "id", "[", "...
// FromBytes convert the byte array representation of `ID` back to `ID`
[ "FromBytes", "convert", "the", "byte", "array", "representation", "of", "ID", "back", "to", "ID" ]
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L340-L347
train
rs/xid
id.go
Compare
func (id ID) Compare(other ID) int { return bytes.Compare(id[:], other[:]) }
go
func (id ID) Compare(other ID) int { return bytes.Compare(id[:], other[:]) }
[ "func", "(", "id", "ID", ")", "Compare", "(", "other", "ID", ")", "int", "{", "return", "bytes", ".", "Compare", "(", "id", "[", ":", "]", ",", "other", "[", ":", "]", ")", "\n", "}" ]
// Compare returns an integer comparing two IDs. It behaves just like `bytes.Compare`. // The result will be 0 if two IDs are identical, -1 if current id is less than the other one, // and 1 if current id is greater than the other.
[ "Compare", "returns", "an", "integer", "comparing", "two", "IDs", ".", "It", "behaves", "just", "like", "bytes", ".", "Compare", ".", "The", "result", "will", "be", "0", "if", "two", "IDs", "are", "identical", "-", "1", "if", "current", "id", "is", "le...
ba6f703301d6c14cbc05faa3b512058f2304e16c
https://github.com/rs/xid/blob/ba6f703301d6c14cbc05faa3b512058f2304e16c/id.go#L352-L354
train
crewjam/saml
xmlenc/fuzz.go
Fuzz
func Fuzz(data []byte) int { doc := etree.NewDocument() if err := doc.ReadFromBytes(data); err != nil { return 0 } if doc.Root() == nil { return 0 } if _, err := Decrypt(testKey, doc.Root()); err != nil { return 0 } return 1 }
go
func Fuzz(data []byte) int { doc := etree.NewDocument() if err := doc.ReadFromBytes(data); err != nil { return 0 } if doc.Root() == nil { return 0 } if _, err := Decrypt(testKey, doc.Root()); err != nil { return 0 } return 1 }
[ "func", "Fuzz", "(", "data", "[", "]", "byte", ")", "int", "{", "doc", ":=", "etree", ".", "NewDocument", "(", ")", "\n", "if", "err", ":=", "doc", ".", "ReadFromBytes", "(", "data", ")", ";", "err", "!=", "nil", "{", "return", "0", "\n", "}", ...
// Fuzz is the go-fuzz fuzzing function
[ "Fuzz", "is", "the", "go", "-", "fuzz", "fuzzing", "function" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/xmlenc/fuzz.go#L36-L49
train
crewjam/saml
samlidp/session.go
sendLoginForm
func (s *Server) sendLoginForm(w http.ResponseWriter, r *http.Request, req *saml.IdpAuthnRequest, toast string) { tmpl := template.Must(template.New("saml-post-form").Parse(`` + `<html>` + `<p>{{.Toast}}</p>` + `<form method="post" action="{{.URL}}">` + `<input type="text" name="user" placeholder="user" value="" />` + `<input type="password" name="password" placeholder="password" value="" />` + `<input type="hidden" name="SAMLRequest" value="{{.SAMLRequest}}" />` + `<input type="hidden" name="RelayState" value="{{.RelayState}}" />` + `<input type="submit" value="Log In" />` + `</form>` + `</html>`)) data := struct { Toast string URL string SAMLRequest string RelayState string }{ Toast: toast, URL: req.IDP.SSOURL.String(), SAMLRequest: base64.StdEncoding.EncodeToString(req.RequestBuffer), RelayState: req.RelayState, } if err := tmpl.Execute(w, data); err != nil { panic(err) } }
go
func (s *Server) sendLoginForm(w http.ResponseWriter, r *http.Request, req *saml.IdpAuthnRequest, toast string) { tmpl := template.Must(template.New("saml-post-form").Parse(`` + `<html>` + `<p>{{.Toast}}</p>` + `<form method="post" action="{{.URL}}">` + `<input type="text" name="user" placeholder="user" value="" />` + `<input type="password" name="password" placeholder="password" value="" />` + `<input type="hidden" name="SAMLRequest" value="{{.SAMLRequest}}" />` + `<input type="hidden" name="RelayState" value="{{.RelayState}}" />` + `<input type="submit" value="Log In" />` + `</form>` + `</html>`)) data := struct { Toast string URL string SAMLRequest string RelayState string }{ Toast: toast, URL: req.IDP.SSOURL.String(), SAMLRequest: base64.StdEncoding.EncodeToString(req.RequestBuffer), RelayState: req.RelayState, } if err := tmpl.Execute(w, data); err != nil { panic(err) } }
[ "func", "(", "s", "*", "Server", ")", "sendLoginForm", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "req", "*", "saml", ".", "IdpAuthnRequest", ",", "toast", "string", ")", "{", "tmpl", ":=", "template", ".", "...
// sendLoginForm produces a form which requests a username and password and directs the user // back to the IDP authorize URL to restart the SAML login flow, this time establishing a // session based on the credentials that were provided.
[ "sendLoginForm", "produces", "a", "form", "which", "requests", "a", "username", "and", "password", "and", "directs", "the", "user", "back", "to", "the", "IDP", "authorize", "URL", "to", "restart", "the", "SAML", "login", "flow", "this", "time", "establishing",...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/session.go#L102-L129
train
crewjam/saml
samlsp/token.go
Get
func (a Attributes) Get(key string) string { if a == nil { return "" } v := a[key] if len(v) == 0 { return "" } return v[0] }
go
func (a Attributes) Get(key string) string { if a == nil { return "" } v := a[key] if len(v) == 0 { return "" } return v[0] }
[ "func", "(", "a", "Attributes", ")", "Get", "(", "key", "string", ")", "string", "{", "if", "a", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "v", ":=", "a", "[", "key", "]", "\n", "if", "len", "(", "v", ")", "==", "0", "{", "re...
// Get returns the first attribute named `key` or an empty string if // no such attributes is present.
[ "Get", "returns", "the", "first", "attribute", "named", "key", "or", "an", "empty", "string", "if", "no", "such", "attributes", "is", "present", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/token.go#L20-L29
train
crewjam/saml
samlsp/token.go
Token
func Token(ctx context.Context) *AuthorizationToken { v := ctx.Value(tokenIndex) if v == nil { return nil } return v.(*AuthorizationToken) }
go
func Token(ctx context.Context) *AuthorizationToken { v := ctx.Value(tokenIndex) if v == nil { return nil } return v.(*AuthorizationToken) }
[ "func", "Token", "(", "ctx", "context", ".", "Context", ")", "*", "AuthorizationToken", "{", "v", ":=", "ctx", ".", "Value", "(", "tokenIndex", ")", "\n", "if", "v", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "v", ".", "(", "*", ...
// Token returns the token associated with ctx, or nil if no token are associated
[ "Token", "returns", "the", "token", "associated", "with", "ctx", "or", "nil", "if", "no", "token", "are", "associated" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/token.go#L36-L42
train
crewjam/saml
samlsp/token.go
WithToken
func WithToken(ctx context.Context, token *AuthorizationToken) context.Context { return context.WithValue(ctx, tokenIndex, token) }
go
func WithToken(ctx context.Context, token *AuthorizationToken) context.Context { return context.WithValue(ctx, tokenIndex, token) }
[ "func", "WithToken", "(", "ctx", "context", ".", "Context", ",", "token", "*", "AuthorizationToken", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "tokenIndex", ",", "token", ")", "\n", "}" ]
// WithToken returns a new context with token associated
[ "WithToken", "returns", "a", "new", "context", "with", "token", "associated" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/token.go#L45-L47
train
crewjam/saml
samlidp/memory_store.go
Get
func (s *MemoryStore) Get(key string, value interface{}) error { s.mu.RLock() defer s.mu.RUnlock() v, ok := s.data[key] if !ok { return ErrNotFound } return json.Unmarshal([]byte(v), value) }
go
func (s *MemoryStore) Get(key string, value interface{}) error { s.mu.RLock() defer s.mu.RUnlock() v, ok := s.data[key] if !ok { return ErrNotFound } return json.Unmarshal([]byte(v), value) }
[ "func", "(", "s", "*", "MemoryStore", ")", "Get", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "v", ",", ...
// Get fetches the data stored in `key` and unmarshals it into `value`.
[ "Get", "fetches", "the", "data", "stored", "in", "key", "and", "unmarshals", "it", "into", "value", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/memory_store.go#L17-L26
train
crewjam/saml
samlidp/memory_store.go
Put
func (s *MemoryStore) Put(key string, value interface{}) error { s.mu.Lock() defer s.mu.Unlock() if s.data == nil { s.data = map[string]string{} } buf, err := json.Marshal(value) if err != nil { return err } s.data[key] = string(buf) return nil }
go
func (s *MemoryStore) Put(key string, value interface{}) error { s.mu.Lock() defer s.mu.Unlock() if s.data == nil { s.data = map[string]string{} } buf, err := json.Marshal(value) if err != nil { return err } s.data[key] = string(buf) return nil }
[ "func", "(", "s", "*", "MemoryStore", ")", "Put", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", "....
// Put marshals `value` and stores it in `key`.
[ "Put", "marshals", "value", "and", "stores", "it", "in", "key", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/memory_store.go#L29-L42
train
crewjam/saml
samlidp/memory_store.go
Delete
func (s *MemoryStore) Delete(key string) error { s.mu.Lock() defer s.mu.Unlock() delete(s.data, key) return nil }
go
func (s *MemoryStore) Delete(key string) error { s.mu.Lock() defer s.mu.Unlock() delete(s.data, key) return nil }
[ "func", "(", "s", "*", "MemoryStore", ")", "Delete", "(", "key", "string", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "delete", "(", "s", ".", "data", ",", "key", ")...
// Delete removes `key`
[ "Delete", "removes", "key" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/memory_store.go#L45-L50
train
crewjam/saml
example/service.go
CreateLink
func CreateLink(c web.C, w http.ResponseWriter, r *http.Request) { account := r.Header.Get("X-Remote-User") l := Link{ ShortLink: uniuri.New(), Target: r.FormValue("t"), Owner: account, } links[l.ShortLink] = l fmt.Fprintf(w, "%s\n", l.ShortLink) return }
go
func CreateLink(c web.C, w http.ResponseWriter, r *http.Request) { account := r.Header.Get("X-Remote-User") l := Link{ ShortLink: uniuri.New(), Target: r.FormValue("t"), Owner: account, } links[l.ShortLink] = l fmt.Fprintf(w, "%s\n", l.ShortLink) return }
[ "func", "CreateLink", "(", "c", "web", ".", "C", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "account", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "l", ":=", "Link", "{", "Sho...
// CreateLink handles requests to create links
[ "CreateLink", "handles", "requests", "to", "create", "links" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/example/service.go#L35-L46
train
crewjam/saml
example/service.go
ServeLink
func ServeLink(c web.C, w http.ResponseWriter, r *http.Request) { l, ok := links[strings.TrimPrefix(r.URL.Path, "/")] if !ok { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } http.Redirect(w, r, l.Target, http.StatusFound) return }
go
func ServeLink(c web.C, w http.ResponseWriter, r *http.Request) { l, ok := links[strings.TrimPrefix(r.URL.Path, "/")] if !ok { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } http.Redirect(w, r, l.Target, http.StatusFound) return }
[ "func", "ServeLink", "(", "c", "web", ".", "C", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "l", ",", "ok", ":=", "links", "[", "strings", ".", "TrimPrefix", "(", "r", ".", "URL", ".", "Path", ",", ...
// ServeLink handles requests to redirect to a link
[ "ServeLink", "handles", "requests", "to", "redirect", "to", "a", "link" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/example/service.go#L49-L57
train
crewjam/saml
example/service.go
ListLinks
func ListLinks(c web.C, w http.ResponseWriter, r *http.Request) { account := r.Header.Get("X-Remote-User") for _, l := range links { if l.Owner == account { fmt.Fprintf(w, "%s\n", l.ShortLink) } } }
go
func ListLinks(c web.C, w http.ResponseWriter, r *http.Request) { account := r.Header.Get("X-Remote-User") for _, l := range links { if l.Owner == account { fmt.Fprintf(w, "%s\n", l.ShortLink) } } }
[ "func", "ListLinks", "(", "c", "web", ".", "C", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "account", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "for", "_", ",", "l", ":=", ...
// ListLinks returns a list of the current user's links
[ "ListLinks", "returns", "a", "list", "of", "the", "current", "user", "s", "links" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/example/service.go#L60-L67
train
crewjam/saml
schema.go
Element
func (r *AuthnRequest) Element() *etree.Element { el := etree.NewElement("samlp:AuthnRequest") el.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion") el.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol") el.CreateAttr("ID", r.ID) el.CreateAttr("Version", r.Version) el.CreateAttr("IssueInstant", r.IssueInstant.Format(timeFormat)) if r.Destination != "" { el.CreateAttr("Destination", r.Destination) } if r.Consent != "" { el.CreateAttr("Consent", r.Consent) } if r.Issuer != nil { el.AddChild(r.Issuer.Element()) } if r.Signature != nil { el.AddChild(r.Signature) } if r.Subject != nil { el.AddChild(r.Subject.Element()) } if r.NameIDPolicy != nil { el.AddChild(r.NameIDPolicy.Element()) } if r.Conditions != nil { el.AddChild(r.Conditions.Element()) } //if r.RequestedAuthnContext != nil { // el.AddChild(r.RequestedAuthnContext.Element()) //} //if r.Scoping != nil { // el.AddChild(r.Scoping.Element()) //} if r.ForceAuthn != nil { el.CreateAttr("ForceAuthn", strconv.FormatBool(*r.ForceAuthn)) } if r.IsPassive != nil { el.CreateAttr("IsPassive", strconv.FormatBool(*r.IsPassive)) } if r.AssertionConsumerServiceIndex != "" { el.CreateAttr("AssertionConsumerServiceIndex", r.AssertionConsumerServiceIndex) } if r.AssertionConsumerServiceURL != "" { el.CreateAttr("AssertionConsumerServiceURL", r.AssertionConsumerServiceURL) } if r.ProtocolBinding != "" { el.CreateAttr("ProtocolBinding", r.ProtocolBinding) } if r.AttributeConsumingServiceIndex != "" { el.CreateAttr("AttributeConsumingServiceIndex", r.AttributeConsumingServiceIndex) } if r.ProviderName != "" { el.CreateAttr("ProviderName", r.ProviderName) } return el }
go
func (r *AuthnRequest) Element() *etree.Element { el := etree.NewElement("samlp:AuthnRequest") el.CreateAttr("xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion") el.CreateAttr("xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol") el.CreateAttr("ID", r.ID) el.CreateAttr("Version", r.Version) el.CreateAttr("IssueInstant", r.IssueInstant.Format(timeFormat)) if r.Destination != "" { el.CreateAttr("Destination", r.Destination) } if r.Consent != "" { el.CreateAttr("Consent", r.Consent) } if r.Issuer != nil { el.AddChild(r.Issuer.Element()) } if r.Signature != nil { el.AddChild(r.Signature) } if r.Subject != nil { el.AddChild(r.Subject.Element()) } if r.NameIDPolicy != nil { el.AddChild(r.NameIDPolicy.Element()) } if r.Conditions != nil { el.AddChild(r.Conditions.Element()) } //if r.RequestedAuthnContext != nil { // el.AddChild(r.RequestedAuthnContext.Element()) //} //if r.Scoping != nil { // el.AddChild(r.Scoping.Element()) //} if r.ForceAuthn != nil { el.CreateAttr("ForceAuthn", strconv.FormatBool(*r.ForceAuthn)) } if r.IsPassive != nil { el.CreateAttr("IsPassive", strconv.FormatBool(*r.IsPassive)) } if r.AssertionConsumerServiceIndex != "" { el.CreateAttr("AssertionConsumerServiceIndex", r.AssertionConsumerServiceIndex) } if r.AssertionConsumerServiceURL != "" { el.CreateAttr("AssertionConsumerServiceURL", r.AssertionConsumerServiceURL) } if r.ProtocolBinding != "" { el.CreateAttr("ProtocolBinding", r.ProtocolBinding) } if r.AttributeConsumingServiceIndex != "" { el.CreateAttr("AttributeConsumingServiceIndex", r.AttributeConsumingServiceIndex) } if r.ProviderName != "" { el.CreateAttr("ProviderName", r.ProviderName) } return el }
[ "func", "(", "r", "*", "AuthnRequest", ")", "Element", "(", ")", "*", "etree", ".", "Element", "{", "el", ":=", "etree", ".", "NewElement", "(", "\"", "\"", ")", "\n", "el", ".", "CreateAttr", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "el", ...
// Element returns an etree.Element representing the object // Element returns an etree.Element representing the object in XML form.
[ "Element", "returns", "an", "etree", ".", "Element", "representing", "the", "object", "Element", "returns", "an", "etree", ".", "Element", "representing", "the", "object", "in", "XML", "form", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/schema.go#L44-L100
train
crewjam/saml
samlsp/middleware.go
ServeHTTP
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Path == m.ServiceProvider.MetadataURL.Path { buf, _ := xml.MarshalIndent(m.ServiceProvider.Metadata(), "", " ") w.Header().Set("Content-Type", "application/samlmetadata+xml") w.Write(buf) return } if r.URL.Path == m.ServiceProvider.AcsURL.Path { r.ParseForm() assertion, err := m.ServiceProvider.ParseResponse(r, m.getPossibleRequestIDs(r)) if err != nil { if parseErr, ok := err.(*saml.InvalidResponseError); ok { m.ServiceProvider.Logger.Printf("RESPONSE: ===\n%s\n===\nNOW: %s\nERROR: %s", parseErr.Response, parseErr.Now, parseErr.PrivateErr) } http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } m.Authorize(w, r, assertion) return } http.NotFoundHandler().ServeHTTP(w, r) }
go
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Path == m.ServiceProvider.MetadataURL.Path { buf, _ := xml.MarshalIndent(m.ServiceProvider.Metadata(), "", " ") w.Header().Set("Content-Type", "application/samlmetadata+xml") w.Write(buf) return } if r.URL.Path == m.ServiceProvider.AcsURL.Path { r.ParseForm() assertion, err := m.ServiceProvider.ParseResponse(r, m.getPossibleRequestIDs(r)) if err != nil { if parseErr, ok := err.(*saml.InvalidResponseError); ok { m.ServiceProvider.Logger.Printf("RESPONSE: ===\n%s\n===\nNOW: %s\nERROR: %s", parseErr.Response, parseErr.Now, parseErr.PrivateErr) } http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } m.Authorize(w, r, assertion) return } http.NotFoundHandler().ServeHTTP(w, r) }
[ "func", "(", "m", "*", "Middleware", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "URL", ".", "Path", "==", "m", ".", "ServiceProvider", ".", "MetadataURL", ".", "Path", ...
// ServeHTTP implements http.Handler and serves the SAML-specific HTTP endpoints // on the URIs specified by m.ServiceProvider.MetadataURL and // m.ServiceProvider.AcsURL.
[ "ServeHTTP", "implements", "http", ".", "Handler", "and", "serves", "the", "SAML", "-", "specific", "HTTP", "endpoints", "on", "the", "URIs", "specified", "by", "m", ".", "ServiceProvider", ".", "MetadataURL", "and", "m", ".", "ServiceProvider", ".", "AcsURL",...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/middleware.go#L67-L92
train
crewjam/saml
samlsp/middleware.go
RequireAccount
func (m *Middleware) RequireAccount(handler http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { if token := m.GetAuthorizationToken(r); token != nil { r = r.WithContext(WithToken(r.Context(), token)) handler.ServeHTTP(w, r) return } m.RequireAccountHandler(w, r) } return http.HandlerFunc(fn) }
go
func (m *Middleware) RequireAccount(handler http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { if token := m.GetAuthorizationToken(r); token != nil { r = r.WithContext(WithToken(r.Context(), token)) handler.ServeHTTP(w, r) return } m.RequireAccountHandler(w, r) } return http.HandlerFunc(fn) }
[ "func", "(", "m", "*", "Middleware", ")", "RequireAccount", "(", "handler", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "fn", ":=", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", ...
// RequireAccount is HTTP middleware that requires that each request be // associated with a valid session. If the request is not associated with a valid // session, then rather than serve the request, the middlware redirects the user // to start the SAML auth flow.
[ "RequireAccount", "is", "HTTP", "middleware", "that", "requires", "that", "each", "request", "be", "associated", "with", "a", "valid", "session", ".", "If", "the", "request", "is", "not", "associated", "with", "a", "valid", "session", "then", "rather", "than",...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/middleware.go#L98-L108
train
crewjam/saml
samlsp/middleware.go
Authorize
func (m *Middleware) Authorize(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) { secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key) redirectURI := "/" if relayState := r.Form.Get("RelayState"); relayState != "" { stateValue := m.ClientState.GetState(r, relayState) if stateValue == "" { m.ServiceProvider.Logger.Printf("cannot find corresponding state: %s", relayState) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } jwtParser := jwt.Parser{ ValidMethods: []string{jwtSigningMethod.Name}, } state, err := jwtParser.Parse(stateValue, func(t *jwt.Token) (interface{}, error) { return secretBlock, nil }) if err != nil || !state.Valid { m.ServiceProvider.Logger.Printf("Cannot decode state JWT: %s (%s)", err, stateValue) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } claims := state.Claims.(jwt.MapClaims) redirectURI = claims["uri"].(string) // delete the cookie m.ClientState.DeleteState(w, r, relayState) } now := saml.TimeNow() claims := AuthorizationToken{} claims.Audience = m.ServiceProvider.Metadata().EntityID claims.IssuedAt = now.Unix() claims.ExpiresAt = now.Add(m.TokenMaxAge).Unix() claims.NotBefore = now.Unix() if sub := assertion.Subject; sub != nil { if nameID := sub.NameID; nameID != nil { claims.StandardClaims.Subject = nameID.Value } } for _, attributeStatement := range assertion.AttributeStatements { claims.Attributes = map[string][]string{} for _, attr := range attributeStatement.Attributes { claimName := attr.FriendlyName if claimName == "" { claimName = attr.Name } for _, value := range attr.Values { claims.Attributes[claimName] = append(claims.Attributes[claimName], value.Value) } } } signedToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secretBlock) if err != nil { panic(err) } m.ClientToken.SetToken(w, r, signedToken, m.TokenMaxAge) http.Redirect(w, r, redirectURI, http.StatusFound) }
go
func (m *Middleware) Authorize(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) { secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key) redirectURI := "/" if relayState := r.Form.Get("RelayState"); relayState != "" { stateValue := m.ClientState.GetState(r, relayState) if stateValue == "" { m.ServiceProvider.Logger.Printf("cannot find corresponding state: %s", relayState) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } jwtParser := jwt.Parser{ ValidMethods: []string{jwtSigningMethod.Name}, } state, err := jwtParser.Parse(stateValue, func(t *jwt.Token) (interface{}, error) { return secretBlock, nil }) if err != nil || !state.Valid { m.ServiceProvider.Logger.Printf("Cannot decode state JWT: %s (%s)", err, stateValue) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } claims := state.Claims.(jwt.MapClaims) redirectURI = claims["uri"].(string) // delete the cookie m.ClientState.DeleteState(w, r, relayState) } now := saml.TimeNow() claims := AuthorizationToken{} claims.Audience = m.ServiceProvider.Metadata().EntityID claims.IssuedAt = now.Unix() claims.ExpiresAt = now.Add(m.TokenMaxAge).Unix() claims.NotBefore = now.Unix() if sub := assertion.Subject; sub != nil { if nameID := sub.NameID; nameID != nil { claims.StandardClaims.Subject = nameID.Value } } for _, attributeStatement := range assertion.AttributeStatements { claims.Attributes = map[string][]string{} for _, attr := range attributeStatement.Attributes { claimName := attr.FriendlyName if claimName == "" { claimName = attr.Name } for _, value := range attr.Values { claims.Attributes[claimName] = append(claims.Attributes[claimName], value.Value) } } } signedToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secretBlock) if err != nil { panic(err) } m.ClientToken.SetToken(w, r, signedToken, m.TokenMaxAge) http.Redirect(w, r, redirectURI, http.StatusFound) }
[ "func", "(", "m", "*", "Middleware", ")", "Authorize", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "assertion", "*", "saml", ".", "Assertion", ")", "{", "secretBlock", ":=", "x509", ".", "MarshalPKCS1PrivateKey", ...
// Authorize is invoked by ServeHTTP when we have a new, valid SAML assertion. // It sets a cookie that contains a signed JWT containing the assertion attributes. // It then redirects the user's browser to the original URL contained in RelayState.
[ "Authorize", "is", "invoked", "by", "ServeHTTP", "when", "we", "have", "a", "new", "valid", "SAML", "assertion", ".", "It", "sets", "a", "cookie", "that", "contains", "a", "signed", "JWT", "containing", "the", "assertion", "attributes", ".", "It", "then", ...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/middleware.go#L204-L265
train
crewjam/saml
samlsp/middleware.go
GetAuthorizationToken
func (m *Middleware) GetAuthorizationToken(r *http.Request) *AuthorizationToken { tokenStr := m.ClientToken.GetToken(r) if tokenStr == "" { return nil } tokenClaims := AuthorizationToken{} token, err := jwt.ParseWithClaims(tokenStr, &tokenClaims, func(t *jwt.Token) (interface{}, error) { secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key) return secretBlock, nil }) if err != nil || !token.Valid { m.ServiceProvider.Logger.Printf("ERROR: invalid token: %s", err) return nil } if err := tokenClaims.StandardClaims.Valid(); err != nil { m.ServiceProvider.Logger.Printf("ERROR: invalid token claims: %s", err) return nil } if tokenClaims.Audience != m.ServiceProvider.Metadata().EntityID { m.ServiceProvider.Logger.Printf("ERROR: tokenClaims.Audience does not match EntityID") return nil } return &tokenClaims }
go
func (m *Middleware) GetAuthorizationToken(r *http.Request) *AuthorizationToken { tokenStr := m.ClientToken.GetToken(r) if tokenStr == "" { return nil } tokenClaims := AuthorizationToken{} token, err := jwt.ParseWithClaims(tokenStr, &tokenClaims, func(t *jwt.Token) (interface{}, error) { secretBlock := x509.MarshalPKCS1PrivateKey(m.ServiceProvider.Key) return secretBlock, nil }) if err != nil || !token.Valid { m.ServiceProvider.Logger.Printf("ERROR: invalid token: %s", err) return nil } if err := tokenClaims.StandardClaims.Valid(); err != nil { m.ServiceProvider.Logger.Printf("ERROR: invalid token claims: %s", err) return nil } if tokenClaims.Audience != m.ServiceProvider.Metadata().EntityID { m.ServiceProvider.Logger.Printf("ERROR: tokenClaims.Audience does not match EntityID") return nil } return &tokenClaims }
[ "func", "(", "m", "*", "Middleware", ")", "GetAuthorizationToken", "(", "r", "*", "http", ".", "Request", ")", "*", "AuthorizationToken", "{", "tokenStr", ":=", "m", ".", "ClientToken", ".", "GetToken", "(", "r", ")", "\n", "if", "tokenStr", "==", "\"", ...
// GetAuthorizationToken is invoked by RequireAccount to determine if the request // is already authorized or if the user's browser should be redirected to the // SAML login flow. If the request is authorized, then the request context is // ammended with a Context object.
[ "GetAuthorizationToken", "is", "invoked", "by", "RequireAccount", "to", "determine", "if", "the", "request", "is", "already", "authorized", "or", "if", "the", "user", "s", "browser", "should", "be", "redirected", "to", "the", "SAML", "login", "flow", ".", "If"...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/middleware.go#L279-L304
train
crewjam/saml
samlidp/shortcut.go
HandleIDPInitiated
func (s *Server) HandleIDPInitiated(c web.C, w http.ResponseWriter, r *http.Request) { shortcutName := c.URLParams["shortcut"] shortcut := Shortcut{} if err := s.Store.Get(fmt.Sprintf("/shortcuts/%s", shortcutName), &shortcut); err != nil { s.logger.Printf("ERROR: %s", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } relayState := "" switch { case shortcut.RelayState != nil: relayState = *shortcut.RelayState case shortcut.URISuffixAsRelayState: relayState, _ = c.URLParams["*"] } s.idpConfigMu.RLock() defer s.idpConfigMu.RUnlock() s.IDP.ServeIDPInitiated(w, r, shortcut.ServiceProviderID, relayState) }
go
func (s *Server) HandleIDPInitiated(c web.C, w http.ResponseWriter, r *http.Request) { shortcutName := c.URLParams["shortcut"] shortcut := Shortcut{} if err := s.Store.Get(fmt.Sprintf("/shortcuts/%s", shortcutName), &shortcut); err != nil { s.logger.Printf("ERROR: %s", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } relayState := "" switch { case shortcut.RelayState != nil: relayState = *shortcut.RelayState case shortcut.URISuffixAsRelayState: relayState, _ = c.URLParams["*"] } s.idpConfigMu.RLock() defer s.idpConfigMu.RUnlock() s.IDP.ServeIDPInitiated(w, r, shortcut.ServiceProviderID, relayState) }
[ "func", "(", "s", "*", "Server", ")", "HandleIDPInitiated", "(", "c", "web", ".", "C", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "shortcutName", ":=", "c", ".", "URLParams", "[", "\"", "\"", "]", "\n"...
// HandleIDPInitiated handles a request for an IDP initiated login flow. It looks up // the specified shortcut, generates the appropriate SAML assertion and redirects the // user via the HTTP-POST binding to the service providers ACS URL.
[ "HandleIDPInitiated", "handles", "a", "request", "for", "an", "IDP", "initiated", "login", "flow", ".", "It", "looks", "up", "the", "specified", "shortcut", "generates", "the", "appropriate", "SAML", "assertion", "and", "redirects", "the", "user", "via", "the", ...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/shortcut.go#L89-L109
train
crewjam/saml
identity_provider.go
Handler
func (idp *IdentityProvider) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc(idp.MetadataURL.Path, idp.ServeMetadata) mux.HandleFunc(idp.SSOURL.Path, idp.ServeSSO) return mux }
go
func (idp *IdentityProvider) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc(idp.MetadataURL.Path, idp.ServeMetadata) mux.HandleFunc(idp.SSOURL.Path, idp.ServeSSO) return mux }
[ "func", "(", "idp", "*", "IdentityProvider", ")", "Handler", "(", ")", "http", ".", "Handler", "{", "mux", ":=", "http", ".", "NewServeMux", "(", ")", "\n", "mux", ".", "HandleFunc", "(", "idp", ".", "MetadataURL", ".", "Path", ",", "idp", ".", "Serv...
// Handler returns an http.Handler that serves the metadata and SSO // URLs
[ "Handler", "returns", "an", "http", ".", "Handler", "that", "serves", "the", "metadata", "and", "SSO", "URLs" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/identity_provider.go#L168-L173
train
crewjam/saml
identity_provider.go
MakeAssertionEl
func (req *IdpAuthnRequest) MakeAssertionEl() error { keyPair := tls.Certificate{ Certificate: [][]byte{req.IDP.Certificate.Raw}, PrivateKey: req.IDP.Key, Leaf: req.IDP.Certificate, } for _, cert := range req.IDP.Intermediates { keyPair.Certificate = append(keyPair.Certificate, cert.Raw) } keyStore := dsig.TLSCertKeyStore(keyPair) signatureMethod := req.IDP.SignatureMethod if signatureMethod == "" { signatureMethod = dsig.RSASHA1SignatureMethod } signingContext := dsig.NewDefaultSigningContext(keyStore) signingContext.Canonicalizer = dsig.MakeC14N10ExclusiveCanonicalizerWithPrefixList(canonicalizerPrefixList) if err := signingContext.SetSignatureMethod(signatureMethod); err != nil { return err } assertionEl := req.Assertion.Element() signedAssertionEl, err := signingContext.SignEnveloped(assertionEl) if err != nil { return err } sigEl := signedAssertionEl.Child[len(signedAssertionEl.Child)-1] req.Assertion.Signature = sigEl.(*etree.Element) signedAssertionEl = req.Assertion.Element() certBuf, err := req.getSPEncryptionCert() if err == os.ErrNotExist { req.AssertionEl = signedAssertionEl return nil } else if err != nil { return err } var signedAssertionBuf []byte { doc := etree.NewDocument() doc.SetRoot(signedAssertionEl) signedAssertionBuf, err = doc.WriteToBytes() if err != nil { return err } } encryptor := xmlenc.OAEP() encryptor.BlockCipher = xmlenc.AES128CBC encryptor.DigestMethod = &xmlenc.SHA1 encryptedDataEl, err := encryptor.Encrypt(certBuf, signedAssertionBuf) if err != nil { return err } encryptedDataEl.CreateAttr("Type", "http://www.w3.org/2001/04/xmlenc#Element") encryptedAssertionEl := etree.NewElement("saml:EncryptedAssertion") encryptedAssertionEl.AddChild(encryptedDataEl) req.AssertionEl = encryptedAssertionEl return nil }
go
func (req *IdpAuthnRequest) MakeAssertionEl() error { keyPair := tls.Certificate{ Certificate: [][]byte{req.IDP.Certificate.Raw}, PrivateKey: req.IDP.Key, Leaf: req.IDP.Certificate, } for _, cert := range req.IDP.Intermediates { keyPair.Certificate = append(keyPair.Certificate, cert.Raw) } keyStore := dsig.TLSCertKeyStore(keyPair) signatureMethod := req.IDP.SignatureMethod if signatureMethod == "" { signatureMethod = dsig.RSASHA1SignatureMethod } signingContext := dsig.NewDefaultSigningContext(keyStore) signingContext.Canonicalizer = dsig.MakeC14N10ExclusiveCanonicalizerWithPrefixList(canonicalizerPrefixList) if err := signingContext.SetSignatureMethod(signatureMethod); err != nil { return err } assertionEl := req.Assertion.Element() signedAssertionEl, err := signingContext.SignEnveloped(assertionEl) if err != nil { return err } sigEl := signedAssertionEl.Child[len(signedAssertionEl.Child)-1] req.Assertion.Signature = sigEl.(*etree.Element) signedAssertionEl = req.Assertion.Element() certBuf, err := req.getSPEncryptionCert() if err == os.ErrNotExist { req.AssertionEl = signedAssertionEl return nil } else if err != nil { return err } var signedAssertionBuf []byte { doc := etree.NewDocument() doc.SetRoot(signedAssertionEl) signedAssertionBuf, err = doc.WriteToBytes() if err != nil { return err } } encryptor := xmlenc.OAEP() encryptor.BlockCipher = xmlenc.AES128CBC encryptor.DigestMethod = &xmlenc.SHA1 encryptedDataEl, err := encryptor.Encrypt(certBuf, signedAssertionBuf) if err != nil { return err } encryptedDataEl.CreateAttr("Type", "http://www.w3.org/2001/04/xmlenc#Element") encryptedAssertionEl := etree.NewElement("saml:EncryptedAssertion") encryptedAssertionEl.AddChild(encryptedDataEl) req.AssertionEl = encryptedAssertionEl return nil }
[ "func", "(", "req", "*", "IdpAuthnRequest", ")", "MakeAssertionEl", "(", ")", "error", "{", "keyPair", ":=", "tls", ".", "Certificate", "{", "Certificate", ":", "[", "]", "[", "]", "byte", "{", "req", ".", "IDP", ".", "Certificate", ".", "Raw", "}", ...
// MakeAssertionEl sets `AssertionEl` to a signed, possibly encrypted, version of `Assertion`.
[ "MakeAssertionEl", "sets", "AssertionEl", "to", "a", "signed", "possibly", "encrypted", "version", "of", "Assertion", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/identity_provider.go#L713-L778
train
crewjam/saml
samlidp/service.go
GetServiceProvider
func (s *Server) GetServiceProvider(r *http.Request, serviceProviderID string) (*saml.EntityDescriptor, error) { s.idpConfigMu.RLock() defer s.idpConfigMu.RUnlock() rv, ok := s.serviceProviders[serviceProviderID] if !ok { return nil, os.ErrNotExist } return rv, nil }
go
func (s *Server) GetServiceProvider(r *http.Request, serviceProviderID string) (*saml.EntityDescriptor, error) { s.idpConfigMu.RLock() defer s.idpConfigMu.RUnlock() rv, ok := s.serviceProviders[serviceProviderID] if !ok { return nil, os.ErrNotExist } return rv, nil }
[ "func", "(", "s", "*", "Server", ")", "GetServiceProvider", "(", "r", "*", "http", ".", "Request", ",", "serviceProviderID", "string", ")", "(", "*", "saml", ".", "EntityDescriptor", ",", "error", ")", "{", "s", ".", "idpConfigMu", ".", "RLock", "(", "...
// GetServiceProvider returns the Service Provider metadata for the // service provider ID, which is typically the service provider's // metadata URL. If an appropriate service provider cannot be found then // the returned error must be os.ErrNotExist.
[ "GetServiceProvider", "returns", "the", "Service", "Provider", "metadata", "for", "the", "service", "provider", "ID", "which", "is", "typically", "the", "service", "provider", "s", "metadata", "URL", ".", "If", "an", "appropriate", "service", "provider", "cannot",...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/service.go#L27-L35
train
crewjam/saml
samlidp/service.go
initializeServices
func (s *Server) initializeServices() error { serviceNames, err := s.Store.List("/services/") if err != nil { return err } for _, serviceName := range serviceNames { service := Service{} if err := s.Store.Get(fmt.Sprintf("/services/%s", serviceName), &service); err != nil { return err } s.idpConfigMu.Lock() s.serviceProviders[service.Metadata.EntityID] = &service.Metadata s.idpConfigMu.Unlock() } return nil }
go
func (s *Server) initializeServices() error { serviceNames, err := s.Store.List("/services/") if err != nil { return err } for _, serviceName := range serviceNames { service := Service{} if err := s.Store.Get(fmt.Sprintf("/services/%s", serviceName), &service); err != nil { return err } s.idpConfigMu.Lock() s.serviceProviders[service.Metadata.EntityID] = &service.Metadata s.idpConfigMu.Unlock() } return nil }
[ "func", "(", "s", "*", "Server", ")", "initializeServices", "(", ")", "error", "{", "serviceNames", ",", "err", ":=", "s", ".", "Store", ".", "List", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fo...
// initializeServices reads all the stored services and initializes the underlying // identity provider to accept them.
[ "initializeServices", "reads", "all", "the", "stored", "services", "and", "initializes", "the", "underlying", "identity", "provider", "to", "accept", "them", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/service.go#L118-L134
train
crewjam/saml
service_provider.go
Element
func (n NameIDFormat) Element() *etree.Element { el := etree.NewElement("") el.SetText(string(n)) return el }
go
func (n NameIDFormat) Element() *etree.Element { el := etree.NewElement("") el.SetText(string(n)) return el }
[ "func", "(", "n", "NameIDFormat", ")", "Element", "(", ")", "*", "etree", ".", "Element", "{", "el", ":=", "etree", ".", "NewElement", "(", "\"", "\"", ")", "\n", "el", ".", "SetText", "(", "string", "(", "n", ")", ")", "\n", "return", "el", "\n"...
// Element returns an XML element representation of n.
[ "Element", "returns", "an", "XML", "element", "representation", "of", "n", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L29-L33
train
crewjam/saml
service_provider.go
Redirect
func (req *AuthnRequest) Redirect(relayState string) *url.URL { w := &bytes.Buffer{} w1 := base64.NewEncoder(base64.StdEncoding, w) w2, _ := flate.NewWriter(w1, 9) doc := etree.NewDocument() doc.SetRoot(req.Element()) if _, err := doc.WriteTo(w2); err != nil { panic(err) } w2.Close() w1.Close() rv, _ := url.Parse(req.Destination) query := rv.Query() query.Set("SAMLRequest", string(w.Bytes())) if relayState != "" { query.Set("RelayState", relayState) } rv.RawQuery = query.Encode() return rv }
go
func (req *AuthnRequest) Redirect(relayState string) *url.URL { w := &bytes.Buffer{} w1 := base64.NewEncoder(base64.StdEncoding, w) w2, _ := flate.NewWriter(w1, 9) doc := etree.NewDocument() doc.SetRoot(req.Element()) if _, err := doc.WriteTo(w2); err != nil { panic(err) } w2.Close() w1.Close() rv, _ := url.Parse(req.Destination) query := rv.Query() query.Set("SAMLRequest", string(w.Bytes())) if relayState != "" { query.Set("RelayState", relayState) } rv.RawQuery = query.Encode() return rv }
[ "func", "(", "req", "*", "AuthnRequest", ")", "Redirect", "(", "relayState", "string", ")", "*", "url", ".", "URL", "{", "w", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "w1", ":=", "base64", ".", "NewEncoder", "(", "base64", ".", "StdEncoding...
// Redirect returns a URL suitable for using the redirect binding with the request
[ "Redirect", "returns", "a", "URL", "suitable", "for", "using", "the", "redirect", "binding", "with", "the", "request" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L171-L193
train
crewjam/saml
service_provider.go
getIDPSigningCerts
func (sp *ServiceProvider) getIDPSigningCerts() ([]*x509.Certificate, error) { var certStrs []string for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors { for _, keyDescriptor := range idpSSODescriptor.KeyDescriptors { if keyDescriptor.Use == "signing" { certStrs = append(certStrs, keyDescriptor.KeyInfo.Certificate) } } } // If there are no explicitly signing certs, just return the first // non-empty cert we find. if len(certStrs) == 0 { for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors { for _, keyDescriptor := range idpSSODescriptor.KeyDescriptors { if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" { certStrs = append(certStrs, keyDescriptor.KeyInfo.Certificate) break } } } } if len(certStrs) == 0 { return nil, errors.New("cannot find any signing certificate in the IDP SSO descriptor") } var certs []*x509.Certificate // cleanup whitespace regex := regexp.MustCompile(`\s+`) for _, certStr := range certStrs { certStr = regex.ReplaceAllString(certStr, "") certBytes, err := base64.StdEncoding.DecodeString(certStr) if err != nil { return nil, fmt.Errorf("cannot parse certificate: %s", err) } parsedCert, err := x509.ParseCertificate(certBytes) if err != nil { return nil, err } certs = append(certs, parsedCert) } return certs, nil }
go
func (sp *ServiceProvider) getIDPSigningCerts() ([]*x509.Certificate, error) { var certStrs []string for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors { for _, keyDescriptor := range idpSSODescriptor.KeyDescriptors { if keyDescriptor.Use == "signing" { certStrs = append(certStrs, keyDescriptor.KeyInfo.Certificate) } } } // If there are no explicitly signing certs, just return the first // non-empty cert we find. if len(certStrs) == 0 { for _, idpSSODescriptor := range sp.IDPMetadata.IDPSSODescriptors { for _, keyDescriptor := range idpSSODescriptor.KeyDescriptors { if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" { certStrs = append(certStrs, keyDescriptor.KeyInfo.Certificate) break } } } } if len(certStrs) == 0 { return nil, errors.New("cannot find any signing certificate in the IDP SSO descriptor") } var certs []*x509.Certificate // cleanup whitespace regex := regexp.MustCompile(`\s+`) for _, certStr := range certStrs { certStr = regex.ReplaceAllString(certStr, "") certBytes, err := base64.StdEncoding.DecodeString(certStr) if err != nil { return nil, fmt.Errorf("cannot parse certificate: %s", err) } parsedCert, err := x509.ParseCertificate(certBytes) if err != nil { return nil, err } certs = append(certs, parsedCert) } return certs, nil }
[ "func", "(", "sp", "*", "ServiceProvider", ")", "getIDPSigningCerts", "(", ")", "(", "[", "]", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "var", "certStrs", "[", "]", "string", "\n", "for", "_", ",", "idpSSODescriptor", ":=", "range", "sp...
// getIDPSigningCerts returns the certificates which we can use to verify things // signed by the IDP in PEM format, or nil if no such certificate is found.
[ "getIDPSigningCerts", "returns", "the", "certificates", "which", "we", "can", "use", "to", "verify", "things", "signed", "by", "the", "IDP", "in", "PEM", "format", "or", "nil", "if", "no", "such", "certificate", "is", "found", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L210-L256
train
crewjam/saml
service_provider.go
validateSigned
func (sp *ServiceProvider) validateSigned(responseEl *etree.Element) error { haveSignature := false // Some SAML responses have the signature on the Response object, and some on the Assertion // object, and some on both. We will require that at least one signature be present and that // all signatures be valid sigEl, err := findChild(responseEl, "http://www.w3.org/2000/09/xmldsig#", "Signature") if err != nil { return err } if sigEl != nil { if err = sp.validateSignature(responseEl); err != nil { return fmt.Errorf("cannot validate signature on Response: %v", err) } haveSignature = true } assertionEl, err := findChild(responseEl, "urn:oasis:names:tc:SAML:2.0:assertion", "Assertion") if err != nil { return err } if assertionEl != nil { sigEl, err := findChild(assertionEl, "http://www.w3.org/2000/09/xmldsig#", "Signature") if err != nil { return err } if sigEl != nil { if err = sp.validateSignature(assertionEl); err != nil { return fmt.Errorf("cannot validate signature on Response: %v", err) } haveSignature = true } } if !haveSignature { return errors.New("either the Response or Assertion must be signed") } return nil }
go
func (sp *ServiceProvider) validateSigned(responseEl *etree.Element) error { haveSignature := false // Some SAML responses have the signature on the Response object, and some on the Assertion // object, and some on both. We will require that at least one signature be present and that // all signatures be valid sigEl, err := findChild(responseEl, "http://www.w3.org/2000/09/xmldsig#", "Signature") if err != nil { return err } if sigEl != nil { if err = sp.validateSignature(responseEl); err != nil { return fmt.Errorf("cannot validate signature on Response: %v", err) } haveSignature = true } assertionEl, err := findChild(responseEl, "urn:oasis:names:tc:SAML:2.0:assertion", "Assertion") if err != nil { return err } if assertionEl != nil { sigEl, err := findChild(assertionEl, "http://www.w3.org/2000/09/xmldsig#", "Signature") if err != nil { return err } if sigEl != nil { if err = sp.validateSignature(assertionEl); err != nil { return fmt.Errorf("cannot validate signature on Response: %v", err) } haveSignature = true } } if !haveSignature { return errors.New("either the Response or Assertion must be signed") } return nil }
[ "func", "(", "sp", "*", "ServiceProvider", ")", "validateSigned", "(", "responseEl", "*", "etree", ".", "Element", ")", "error", "{", "haveSignature", ":=", "false", "\n\n", "// Some SAML responses have the signature on the Response object, and some on the Assertion", "// o...
// validateSigned returns a nil error iff each of the signatures on the Response and Assertion elements // are valid and there is at least one signature.
[ "validateSigned", "returns", "a", "nil", "error", "iff", "each", "of", "the", "signatures", "on", "the", "Response", "and", "Assertion", "elements", "are", "valid", "and", "there", "is", "at", "least", "one", "signature", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L594-L632
train
crewjam/saml
service_provider.go
validateSignature
func (sp *ServiceProvider) validateSignature(el *etree.Element) error { certs, err := sp.getIDPSigningCerts() if err != nil { return err } certificateStore := dsig.MemoryX509CertificateStore{ Roots: certs, } validationContext := dsig.NewDefaultValidationContext(&certificateStore) validationContext.IdAttribute = "ID" if Clock != nil { validationContext.Clock = Clock } // Some SAML responses contain a RSAKeyValue element. One of two things is happening here: // // (1) We're getting something signed by a key we already know about -- the public key // of the signing cert provided in the metadata. // (2) We're getting something signed by a key we *don't* know about, and which we have // no ability to verify. // // The best course of action is to just remove the KeyInfo so that dsig falls back to // verifying against the public key provided in the metadata. if el.FindElement("./Signature/KeyInfo/X509Data/X509Certificate") == nil { if sigEl := el.FindElement("./Signature"); sigEl != nil { if keyInfo := sigEl.FindElement("KeyInfo"); keyInfo != nil { sigEl.RemoveChild(keyInfo) } } } ctx, err := etreeutils.NSBuildParentContext(el) if err != nil { return err } ctx, err = ctx.SubContext(el) if err != nil { return err } el, err = etreeutils.NSDetatch(ctx, el) if err != nil { return err } _, err = validationContext.Validate(el) return err }
go
func (sp *ServiceProvider) validateSignature(el *etree.Element) error { certs, err := sp.getIDPSigningCerts() if err != nil { return err } certificateStore := dsig.MemoryX509CertificateStore{ Roots: certs, } validationContext := dsig.NewDefaultValidationContext(&certificateStore) validationContext.IdAttribute = "ID" if Clock != nil { validationContext.Clock = Clock } // Some SAML responses contain a RSAKeyValue element. One of two things is happening here: // // (1) We're getting something signed by a key we already know about -- the public key // of the signing cert provided in the metadata. // (2) We're getting something signed by a key we *don't* know about, and which we have // no ability to verify. // // The best course of action is to just remove the KeyInfo so that dsig falls back to // verifying against the public key provided in the metadata. if el.FindElement("./Signature/KeyInfo/X509Data/X509Certificate") == nil { if sigEl := el.FindElement("./Signature"); sigEl != nil { if keyInfo := sigEl.FindElement("KeyInfo"); keyInfo != nil { sigEl.RemoveChild(keyInfo) } } } ctx, err := etreeutils.NSBuildParentContext(el) if err != nil { return err } ctx, err = ctx.SubContext(el) if err != nil { return err } el, err = etreeutils.NSDetatch(ctx, el) if err != nil { return err } _, err = validationContext.Validate(el) return err }
[ "func", "(", "sp", "*", "ServiceProvider", ")", "validateSignature", "(", "el", "*", "etree", ".", "Element", ")", "error", "{", "certs", ",", "err", ":=", "sp", ".", "getIDPSigningCerts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err",...
// validateSignature returns nill iff the Signature embedded in the element is valid
[ "validateSignature", "returns", "nill", "iff", "the", "Signature", "embedded", "in", "the", "element", "is", "valid" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/service_provider.go#L635-L683
train
crewjam/saml
samlidp/samlidp.go
New
func New(opts Options) (*Server, error) { metadataURL := opts.URL metadataURL.Path = metadataURL.Path + "/metadata" ssoURL := opts.URL ssoURL.Path = ssoURL.Path + "/sso" logr := opts.Logger if logr == nil { logr = logger.DefaultLogger } s := &Server{ serviceProviders: map[string]*saml.EntityDescriptor{}, IDP: saml.IdentityProvider{ Key: opts.Key, Logger: logr, Certificate: opts.Certificate, MetadataURL: metadataURL, SSOURL: ssoURL, }, logger: logr, Store: opts.Store, } s.IDP.SessionProvider = s s.IDP.ServiceProviderProvider = s if err := s.initializeServices(); err != nil { return nil, err } s.InitializeHTTP() return s, nil }
go
func New(opts Options) (*Server, error) { metadataURL := opts.URL metadataURL.Path = metadataURL.Path + "/metadata" ssoURL := opts.URL ssoURL.Path = ssoURL.Path + "/sso" logr := opts.Logger if logr == nil { logr = logger.DefaultLogger } s := &Server{ serviceProviders: map[string]*saml.EntityDescriptor{}, IDP: saml.IdentityProvider{ Key: opts.Key, Logger: logr, Certificate: opts.Certificate, MetadataURL: metadataURL, SSOURL: ssoURL, }, logger: logr, Store: opts.Store, } s.IDP.SessionProvider = s s.IDP.ServiceProviderProvider = s if err := s.initializeServices(); err != nil { return nil, err } s.InitializeHTTP() return s, nil }
[ "func", "New", "(", "opts", "Options", ")", "(", "*", "Server", ",", "error", ")", "{", "metadataURL", ":=", "opts", ".", "URL", "\n", "metadataURL", ".", "Path", "=", "metadataURL", ".", "Path", "+", "\"", "\"", "\n", "ssoURL", ":=", "opts", ".", ...
// New returns a new Server
[ "New", "returns", "a", "new", "Server" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlidp/samlidp.go#L46-L77
train
crewjam/saml
samlsp/cookie.go
SetState
func (c ClientCookies) SetState(w http.ResponseWriter, r *http.Request, id string, value string) { http.SetCookie(w, &http.Cookie{ Name: stateCookiePrefix + id, Value: value, MaxAge: int(saml.MaxIssueDelay.Seconds()), HttpOnly: true, Secure: c.Secure || r.URL.Scheme == "https", Path: c.ServiceProvider.AcsURL.Path, }) }
go
func (c ClientCookies) SetState(w http.ResponseWriter, r *http.Request, id string, value string) { http.SetCookie(w, &http.Cookie{ Name: stateCookiePrefix + id, Value: value, MaxAge: int(saml.MaxIssueDelay.Seconds()), HttpOnly: true, Secure: c.Secure || r.URL.Scheme == "https", Path: c.ServiceProvider.AcsURL.Path, }) }
[ "func", "(", "c", "ClientCookies", ")", "SetState", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "id", "string", ",", "value", "string", ")", "{", "http", ".", "SetCookie", "(", "w", ",", "&", "http", ".", "C...
// SetState stores the named state value by setting a cookie.
[ "SetState", "stores", "the", "named", "state", "value", "by", "setting", "a", "cookie", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L37-L46
train
crewjam/saml
samlsp/cookie.go
GetStates
func (c ClientCookies) GetStates(r *http.Request) map[string]string { rv := map[string]string{} for _, cookie := range r.Cookies() { if !strings.HasPrefix(cookie.Name, stateCookiePrefix) { continue } name := strings.TrimPrefix(cookie.Name, stateCookiePrefix) rv[name] = cookie.Value } return rv }
go
func (c ClientCookies) GetStates(r *http.Request) map[string]string { rv := map[string]string{} for _, cookie := range r.Cookies() { if !strings.HasPrefix(cookie.Name, stateCookiePrefix) { continue } name := strings.TrimPrefix(cookie.Name, stateCookiePrefix) rv[name] = cookie.Value } return rv }
[ "func", "(", "c", "ClientCookies", ")", "GetStates", "(", "r", "*", "http", ".", "Request", ")", "map", "[", "string", "]", "string", "{", "rv", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "_", ",", "cookie", ":=", "range", ...
// GetStates returns the currently stored states by reading cookies.
[ "GetStates", "returns", "the", "currently", "stored", "states", "by", "reading", "cookies", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L49-L59
train
crewjam/saml
samlsp/cookie.go
GetState
func (c ClientCookies) GetState(r *http.Request, id string) string { stateCookie, err := r.Cookie(stateCookiePrefix + id) if err != nil { return "" } return stateCookie.Value }
go
func (c ClientCookies) GetState(r *http.Request, id string) string { stateCookie, err := r.Cookie(stateCookiePrefix + id) if err != nil { return "" } return stateCookie.Value }
[ "func", "(", "c", "ClientCookies", ")", "GetState", "(", "r", "*", "http", ".", "Request", ",", "id", "string", ")", "string", "{", "stateCookie", ",", "err", ":=", "r", ".", "Cookie", "(", "stateCookiePrefix", "+", "id", ")", "\n", "if", "err", "!="...
// GetState returns a single stored state by reading the cookies
[ "GetState", "returns", "a", "single", "stored", "state", "by", "reading", "the", "cookies" ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L62-L68
train
crewjam/saml
samlsp/cookie.go
DeleteState
func (c ClientCookies) DeleteState(w http.ResponseWriter, r *http.Request, id string) error { cookie, err := r.Cookie(stateCookiePrefix + id) if err != nil { return err } cookie.Value = "" cookie.Expires = time.Unix(1, 0) // past time as close to epoch as possible, but not zero time.Time{} http.SetCookie(w, cookie) return nil }
go
func (c ClientCookies) DeleteState(w http.ResponseWriter, r *http.Request, id string) error { cookie, err := r.Cookie(stateCookiePrefix + id) if err != nil { return err } cookie.Value = "" cookie.Expires = time.Unix(1, 0) // past time as close to epoch as possible, but not zero time.Time{} http.SetCookie(w, cookie) return nil }
[ "func", "(", "c", "ClientCookies", ")", "DeleteState", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "id", "string", ")", "error", "{", "cookie", ",", "err", ":=", "r", ".", "Cookie", "(", "stateCookiePrefix", "+"...
// DeleteState removes the named stored state by clearing the corresponding cookie.
[ "DeleteState", "removes", "the", "named", "stored", "state", "by", "clearing", "the", "corresponding", "cookie", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L71-L80
train
crewjam/saml
samlsp/cookie.go
SetToken
func (c ClientCookies) SetToken(w http.ResponseWriter, r *http.Request, value string, maxAge time.Duration) { http.SetCookie(w, &http.Cookie{ Name: c.Name, Domain: c.Domain, Value: value, MaxAge: int(maxAge.Seconds()), HttpOnly: true, Secure: c.Secure || r.URL.Scheme == "https", Path: "/", }) }
go
func (c ClientCookies) SetToken(w http.ResponseWriter, r *http.Request, value string, maxAge time.Duration) { http.SetCookie(w, &http.Cookie{ Name: c.Name, Domain: c.Domain, Value: value, MaxAge: int(maxAge.Seconds()), HttpOnly: true, Secure: c.Secure || r.URL.Scheme == "https", Path: "/", }) }
[ "func", "(", "c", "ClientCookies", ")", "SetToken", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "value", "string", ",", "maxAge", "time", ".", "Duration", ")", "{", "http", ".", "SetCookie", "(", "w", ",", "&"...
// SetToken assigns the specified token by setting a cookie.
[ "SetToken", "assigns", "the", "specified", "token", "by", "setting", "a", "cookie", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L83-L93
train
crewjam/saml
samlsp/cookie.go
GetToken
func (c ClientCookies) GetToken(r *http.Request) string { cookie, err := r.Cookie(c.Name) if err != nil { return "" } return cookie.Value }
go
func (c ClientCookies) GetToken(r *http.Request) string { cookie, err := r.Cookie(c.Name) if err != nil { return "" } return cookie.Value }
[ "func", "(", "c", "ClientCookies", ")", "GetToken", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "cookie", ",", "err", ":=", "r", ".", "Cookie", "(", "c", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ...
// GetToken returns the token by reading the cookie.
[ "GetToken", "returns", "the", "token", "by", "reading", "the", "cookie", "." ]
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/samlsp/cookie.go#L96-L102
train
crewjam/saml
xmlenc/pubkey.go
OAEP
func OAEP() RSA { return RSA{ BlockCipher: AES256CBC, DigestMethod: SHA256, algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p", keyEncrypter: func(e RSA, pubKey *rsa.PublicKey, plaintext []byte) ([]byte, error) { return rsa.EncryptOAEP(e.DigestMethod.Hash(), RandReader, pubKey, plaintext, nil) }, keyDecrypter: func(e RSA, privKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) { return rsa.DecryptOAEP(e.DigestMethod.Hash(), RandReader, privKey, ciphertext, nil) }, } }
go
func OAEP() RSA { return RSA{ BlockCipher: AES256CBC, DigestMethod: SHA256, algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p", keyEncrypter: func(e RSA, pubKey *rsa.PublicKey, plaintext []byte) ([]byte, error) { return rsa.EncryptOAEP(e.DigestMethod.Hash(), RandReader, pubKey, plaintext, nil) }, keyDecrypter: func(e RSA, privKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) { return rsa.DecryptOAEP(e.DigestMethod.Hash(), RandReader, privKey, ciphertext, nil) }, } }
[ "func", "OAEP", "(", ")", "RSA", "{", "return", "RSA", "{", "BlockCipher", ":", "AES256CBC", ",", "DigestMethod", ":", "SHA256", ",", "algorithm", ":", "\"", "\"", ",", "keyEncrypter", ":", "func", "(", "e", "RSA", ",", "pubKey", "*", "rsa", ".", "Pu...
// OAEP returns a version of RSA that implements RSA in OAEP-MGF1P mode. By default // the block cipher used is AES-256 CBC and the digest method is SHA-256. You can // specify other ciphers and digest methods by assigning to BlockCipher or // DigestMethod.
[ "OAEP", "returns", "a", "version", "of", "RSA", "that", "implements", "RSA", "in", "OAEP", "-", "MGF1P", "mode", ".", "By", "default", "the", "block", "cipher", "used", "is", "AES", "-", "256", "CBC", "and", "the", "digest", "method", "is", "SHA", "-",...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/xmlenc/pubkey.go#L127-L139
train
crewjam/saml
xmlenc/pubkey.go
PKCS1v15
func PKCS1v15() RSA { return RSA{ BlockCipher: AES256CBC, DigestMethod: nil, algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-1_5", keyEncrypter: func(e RSA, pubKey *rsa.PublicKey, plaintext []byte) ([]byte, error) { return rsa.EncryptPKCS1v15(RandReader, pubKey, plaintext) }, keyDecrypter: func(e RSA, privKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) { return rsa.DecryptPKCS1v15(RandReader, privKey, ciphertext) }, } }
go
func PKCS1v15() RSA { return RSA{ BlockCipher: AES256CBC, DigestMethod: nil, algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-1_5", keyEncrypter: func(e RSA, pubKey *rsa.PublicKey, plaintext []byte) ([]byte, error) { return rsa.EncryptPKCS1v15(RandReader, pubKey, plaintext) }, keyDecrypter: func(e RSA, privKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error) { return rsa.DecryptPKCS1v15(RandReader, privKey, ciphertext) }, } }
[ "func", "PKCS1v15", "(", ")", "RSA", "{", "return", "RSA", "{", "BlockCipher", ":", "AES256CBC", ",", "DigestMethod", ":", "nil", ",", "algorithm", ":", "\"", "\"", ",", "keyEncrypter", ":", "func", "(", "e", "RSA", ",", "pubKey", "*", "rsa", ".", "P...
// PKCS1v15 returns a version of RSA that implements RSA in PKCS1v15 mode. By default // the block cipher used is AES-256 CBC. The DigestMethod field is ignored because PKCS1v15 // does not use a digest function.
[ "PKCS1v15", "returns", "a", "version", "of", "RSA", "that", "implements", "RSA", "in", "PKCS1v15", "mode", ".", "By", "default", "the", "block", "cipher", "used", "is", "AES", "-", "256", "CBC", ".", "The", "DigestMethod", "field", "is", "ignored", "becaus...
724cb1c4fab17ba90fa24c4dde8f6f594d105071
https://github.com/crewjam/saml/blob/724cb1c4fab17ba90fa24c4dde8f6f594d105071/xmlenc/pubkey.go#L144-L156
train
tidwall/redcon
append.go
AppendUint
func AppendUint(b []byte, n uint64) []byte { b = append(b, ':') b = strconv.AppendUint(b, n, 10) return append(b, '\r', '\n') }
go
func AppendUint(b []byte, n uint64) []byte { b = append(b, ':') b = strconv.AppendUint(b, n, 10) return append(b, '\r', '\n') }
[ "func", "AppendUint", "(", "b", "[", "]", "byte", ",", "n", "uint64", ")", "[", "]", "byte", "{", "b", "=", "append", "(", "b", ",", "':'", ")", "\n", "b", "=", "strconv", ".", "AppendUint", "(", "b", ",", "n", ",", "10", ")", "\n", "return",...
// AppendUint appends a Redis protocol uint64 to the input bytes.
[ "AppendUint", "appends", "a", "Redis", "protocol", "uint64", "to", "the", "input", "bytes", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L243-L247
train
tidwall/redcon
append.go
AppendArray
func AppendArray(b []byte, n int) []byte { return appendPrefix(b, '*', int64(n)) }
go
func AppendArray(b []byte, n int) []byte { return appendPrefix(b, '*', int64(n)) }
[ "func", "AppendArray", "(", "b", "[", "]", "byte", ",", "n", "int", ")", "[", "]", "byte", "{", "return", "appendPrefix", "(", "b", ",", "'*'", ",", "int64", "(", "n", ")", ")", "\n", "}" ]
// AppendArray appends a Redis protocol array to the input bytes.
[ "AppendArray", "appends", "a", "Redis", "protocol", "array", "to", "the", "input", "bytes", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L255-L257
train
tidwall/redcon
append.go
AppendBulk
func AppendBulk(b []byte, bulk []byte) []byte { b = appendPrefix(b, '$', int64(len(bulk))) b = append(b, bulk...) return append(b, '\r', '\n') }
go
func AppendBulk(b []byte, bulk []byte) []byte { b = appendPrefix(b, '$', int64(len(bulk))) b = append(b, bulk...) return append(b, '\r', '\n') }
[ "func", "AppendBulk", "(", "b", "[", "]", "byte", ",", "bulk", "[", "]", "byte", ")", "[", "]", "byte", "{", "b", "=", "appendPrefix", "(", "b", ",", "'$'", ",", "int64", "(", "len", "(", "bulk", ")", ")", ")", "\n", "b", "=", "append", "(", ...
// AppendBulk appends a Redis protocol bulk byte slice to the input bytes.
[ "AppendBulk", "appends", "a", "Redis", "protocol", "bulk", "byte", "slice", "to", "the", "input", "bytes", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L260-L264
train
tidwall/redcon
append.go
AppendBulkString
func AppendBulkString(b []byte, bulk string) []byte { b = appendPrefix(b, '$', int64(len(bulk))) b = append(b, bulk...) return append(b, '\r', '\n') }
go
func AppendBulkString(b []byte, bulk string) []byte { b = appendPrefix(b, '$', int64(len(bulk))) b = append(b, bulk...) return append(b, '\r', '\n') }
[ "func", "AppendBulkString", "(", "b", "[", "]", "byte", ",", "bulk", "string", ")", "[", "]", "byte", "{", "b", "=", "appendPrefix", "(", "b", ",", "'$'", ",", "int64", "(", "len", "(", "bulk", ")", ")", ")", "\n", "b", "=", "append", "(", "b",...
// AppendBulkString appends a Redis protocol bulk string to the input bytes.
[ "AppendBulkString", "appends", "a", "Redis", "protocol", "bulk", "string", "to", "the", "input", "bytes", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L267-L271
train
tidwall/redcon
append.go
AppendString
func AppendString(b []byte, s string) []byte { b = append(b, '+') b = append(b, stripNewlines(s)...) return append(b, '\r', '\n') }
go
func AppendString(b []byte, s string) []byte { b = append(b, '+') b = append(b, stripNewlines(s)...) return append(b, '\r', '\n') }
[ "func", "AppendString", "(", "b", "[", "]", "byte", ",", "s", "string", ")", "[", "]", "byte", "{", "b", "=", "append", "(", "b", ",", "'+'", ")", "\n", "b", "=", "append", "(", "b", ",", "stripNewlines", "(", "s", ")", "...", ")", "\n", "ret...
// AppendString appends a Redis protocol string to the input bytes.
[ "AppendString", "appends", "a", "Redis", "protocol", "string", "to", "the", "input", "bytes", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L274-L278
train
tidwall/redcon
append.go
AppendError
func AppendError(b []byte, s string) []byte { b = append(b, '-') b = append(b, stripNewlines(s)...) return append(b, '\r', '\n') }
go
func AppendError(b []byte, s string) []byte { b = append(b, '-') b = append(b, stripNewlines(s)...) return append(b, '\r', '\n') }
[ "func", "AppendError", "(", "b", "[", "]", "byte", ",", "s", "string", ")", "[", "]", "byte", "{", "b", "=", "append", "(", "b", ",", "'-'", ")", "\n", "b", "=", "append", "(", "b", ",", "stripNewlines", "(", "s", ")", "...", ")", "\n", "retu...
// AppendError appends a Redis protocol error to the input bytes.
[ "AppendError", "appends", "a", "Redis", "protocol", "error", "to", "the", "input", "bytes", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L281-L285
train
tidwall/redcon
append.go
AppendTile38
func AppendTile38(b []byte, data []byte) []byte { b = append(b, '$') b = strconv.AppendInt(b, int64(len(data)), 10) b = append(b, ' ') b = append(b, data...) return append(b, '\r', '\n') }
go
func AppendTile38(b []byte, data []byte) []byte { b = append(b, '$') b = strconv.AppendInt(b, int64(len(data)), 10) b = append(b, ' ') b = append(b, data...) return append(b, '\r', '\n') }
[ "func", "AppendTile38", "(", "b", "[", "]", "byte", ",", "data", "[", "]", "byte", ")", "[", "]", "byte", "{", "b", "=", "append", "(", "b", ",", "'$'", ")", "\n", "b", "=", "strconv", ".", "AppendInt", "(", "b", ",", "int64", "(", "len", "("...
// AppendTile38 appends a Tile38 message to the input bytes.
[ "AppendTile38", "appends", "a", "Tile38", "message", "to", "the", "input", "bytes", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/append.go#L303-L309
train
tidwall/redcon
redcon.go
NewServer
func NewServer(addr string, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), ) *Server { return NewServerNetwork("tcp", addr, handler, accept, closed) }
go
func NewServer(addr string, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), ) *Server { return NewServerNetwork("tcp", addr, handler, accept, closed) }
[ "func", "NewServer", "(", "addr", "string", ",", "handler", "func", "(", "conn", "Conn", ",", "cmd", "Command", ")", ",", "accept", "func", "(", "conn", "Conn", ")", "bool", ",", "closed", "func", "(", "conn", "Conn", ",", "err", "error", ")", ",", ...
// NewServer returns a new Redcon server configured on "tcp" network net.
[ "NewServer", "returns", "a", "new", "Redcon", "server", "configured", "on", "tcp", "network", "net", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L96-L102
train
tidwall/redcon
redcon.go
NewServerTLS
func NewServerTLS(addr string, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), config *tls.Config, ) *TLSServer { return NewServerNetworkTLS("tcp", addr, handler, accept, closed, config) }
go
func NewServerTLS(addr string, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), config *tls.Config, ) *TLSServer { return NewServerNetworkTLS("tcp", addr, handler, accept, closed, config) }
[ "func", "NewServerTLS", "(", "addr", "string", ",", "handler", "func", "(", "conn", "Conn", ",", "cmd", "Command", ")", ",", "accept", "func", "(", "conn", "Conn", ")", "bool", ",", "closed", "func", "(", "conn", "Conn", ",", "err", "error", ")", ","...
// NewServerTLS returns a new Redcon TLS server configured on "tcp" network net.
[ "NewServerTLS", "returns", "a", "new", "Redcon", "TLS", "server", "configured", "on", "tcp", "network", "net", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L105-L112
train
tidwall/redcon
redcon.go
Close
func (s *Server) Close() error { s.mu.Lock() defer s.mu.Unlock() if s.ln == nil { return errors.New("not serving") } s.done = true return s.ln.Close() }
go
func (s *Server) Close() error { s.mu.Lock() defer s.mu.Unlock() if s.ln == nil { return errors.New("not serving") } s.done = true return s.ln.Close() }
[ "func", "(", "s", "*", "Server", ")", "Close", "(", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "ln", "==", "nil", "{", "return", "errors", ".", "Ne...
// Close stops listening on the TCP address. // Already Accepted connections will be closed.
[ "Close", "stops", "listening", "on", "the", "TCP", "address", ".", "Already", "Accepted", "connections", "will", "be", "closed", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L166-L174
train
tidwall/redcon
redcon.go
Serve
func Serve(ln net.Listener, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), ) error { s := &Server{ net: ln.Addr().Network(), laddr: ln.Addr().String(), ln: ln, handler: handler, accept: accept, closed: closed, conns: make(map[*conn]bool), } return serve(s) }
go
func Serve(ln net.Listener, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), ) error { s := &Server{ net: ln.Addr().Network(), laddr: ln.Addr().String(), ln: ln, handler: handler, accept: accept, closed: closed, conns: make(map[*conn]bool), } return serve(s) }
[ "func", "Serve", "(", "ln", "net", ".", "Listener", ",", "handler", "func", "(", "conn", "Conn", ",", "cmd", "Command", ")", ",", "accept", "func", "(", "conn", "Conn", ")", "bool", ",", "closed", "func", "(", "conn", "Conn", ",", "err", "error", "...
// Serve creates a new server and serves with the given net.Listener.
[ "Serve", "creates", "a", "new", "server", "and", "serves", "with", "the", "given", "net", ".", "Listener", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L204-L220
train
tidwall/redcon
redcon.go
ListenAndServe
func ListenAndServe(addr string, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), ) error { return ListenAndServeNetwork("tcp", addr, handler, accept, closed) }
go
func ListenAndServe(addr string, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), ) error { return ListenAndServeNetwork("tcp", addr, handler, accept, closed) }
[ "func", "ListenAndServe", "(", "addr", "string", ",", "handler", "func", "(", "conn", "Conn", ",", "cmd", "Command", ")", ",", "accept", "func", "(", "conn", "Conn", ")", "bool", ",", "closed", "func", "(", "conn", "Conn", ",", "err", "error", ")", "...
// ListenAndServe creates a new server and binds to addr configured on "tcp" network net.
[ "ListenAndServe", "creates", "a", "new", "server", "and", "binds", "to", "addr", "configured", "on", "tcp", "network", "net", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L223-L229
train
tidwall/redcon
redcon.go
ListenAndServeTLS
func ListenAndServeTLS(addr string, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), config *tls.Config, ) error { return ListenAndServeNetworkTLS("tcp", addr, handler, accept, closed, config) }
go
func ListenAndServeTLS(addr string, handler func(conn Conn, cmd Command), accept func(conn Conn) bool, closed func(conn Conn, err error), config *tls.Config, ) error { return ListenAndServeNetworkTLS("tcp", addr, handler, accept, closed, config) }
[ "func", "ListenAndServeTLS", "(", "addr", "string", ",", "handler", "func", "(", "conn", "Conn", ",", "cmd", "Command", ")", ",", "accept", "func", "(", "conn", "Conn", ")", "bool", ",", "closed", "func", "(", "conn", "Conn", ",", "err", "error", ")", ...
// ListenAndServeTLS creates a new TLS server and binds to addr configured on "tcp" network net.
[ "ListenAndServeTLS", "creates", "a", "new", "TLS", "server", "and", "binds", "to", "addr", "configured", "on", "tcp", "network", "net", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L232-L239
train
tidwall/redcon
redcon.go
ListenServeAndSignal
func (s *Server) ListenServeAndSignal(signal chan error) error { ln, err := net.Listen(s.net, s.laddr) if err != nil { if signal != nil { signal <- err } return err } s.ln = ln if signal != nil { signal <- nil } return serve(s) }
go
func (s *Server) ListenServeAndSignal(signal chan error) error { ln, err := net.Listen(s.net, s.laddr) if err != nil { if signal != nil { signal <- err } return err } s.ln = ln if signal != nil { signal <- nil } return serve(s) }
[ "func", "(", "s", "*", "Server", ")", "ListenServeAndSignal", "(", "signal", "chan", "error", ")", "error", "{", "ln", ",", "err", ":=", "net", ".", "Listen", "(", "s", ".", "net", ",", "s", ".", "laddr", ")", "\n", "if", "err", "!=", "nil", "{",...
// ListenServeAndSignal serves incoming connections and passes nil or error // when listening. signal can be nil.
[ "ListenServeAndSignal", "serves", "incoming", "connections", "and", "passes", "nil", "or", "error", "when", "listening", ".", "signal", "can", "be", "nil", "." ]
c964c660adb68a16a0f890ceb01d25e05d0ab49e
https://github.com/tidwall/redcon/blob/c964c660adb68a16a0f890ceb01d25e05d0ab49e/redcon.go#L266-L279
train