You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.7 KiB
70 lines
1.7 KiB
9 years ago
|
/*
|
||
9 years ago
|
* Minio Cloud Storage, (C) 2015 Minio, Inc.
|
||
9 years ago
|
*
|
||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||
|
* you may not use this file except in compliance with the License.
|
||
|
* You may obtain a copy of the License at
|
||
|
*
|
||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||
|
*
|
||
|
* Unless required by applicable law or agreed to in writing, software
|
||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||
|
* See the License for the specific language governing permissions and
|
||
|
* limitations under the License.
|
||
|
*/
|
||
|
|
||
|
package minhttp
|
||
|
|
||
|
import (
|
||
|
"net"
|
||
9 years ago
|
"os"
|
||
9 years ago
|
"sync"
|
||
|
)
|
||
|
|
||
|
// rateLimitedListener returns a Listener that accepts at most n simultaneous
|
||
|
// connections from the provided Listener.
|
||
|
func rateLimitedListener(l net.Listener, nconn int) net.Listener {
|
||
9 years ago
|
if nconn > 0 {
|
||
|
return &rateLimitListener{l, make(chan struct{}, nconn)}
|
||
|
}
|
||
|
return l
|
||
9 years ago
|
}
|
||
|
|
||
|
type rateLimitListener struct {
|
||
|
net.Listener
|
||
|
sem chan struct{}
|
||
|
}
|
||
|
|
||
|
func (l *rateLimitListener) accept() { l.sem <- struct{}{} }
|
||
|
func (l *rateLimitListener) release() { <-l.sem }
|
||
|
|
||
9 years ago
|
// File - necessary to expose underlying socket fd
|
||
|
func (l *rateLimitListener) File() (f *os.File, err error) {
|
||
|
return l.Listener.(fileListener).File()
|
||
|
}
|
||
|
|
||
|
// Accept - accept method for accepting new connections
|
||
9 years ago
|
func (l *rateLimitListener) Accept() (net.Conn, error) {
|
||
|
l.accept()
|
||
|
|
||
|
c, err := l.Listener.Accept()
|
||
|
if err != nil {
|
||
|
l.release()
|
||
9 years ago
|
return nil, err
|
||
9 years ago
|
}
|
||
|
return &rateLimitListenerConn{Conn: c, release: l.release}, nil
|
||
|
}
|
||
|
|
||
|
type rateLimitListenerConn struct {
|
||
|
net.Conn
|
||
|
releaseOnce sync.Once
|
||
|
release func()
|
||
|
}
|
||
|
|
||
|
func (l *rateLimitListenerConn) Close() error {
|
||
|
err := l.Conn.Close()
|
||
|
l.releaseOnce.Do(l.release)
|
||
9 years ago
|
return err
|
||
9 years ago
|
}
|