Best Gauge code snippet using conn.Close
socket_server.go
Source:socket_server.go
...45 return nil46}47func (s *SocketServer) OnStop() {48 s.BaseService.OnStop()49 if err := s.listener.Close(); err != nil {50 s.Logger.Error("Error closing listener", "err", err)51 }52 s.connsMtx.Lock()53 defer s.connsMtx.Unlock()54 for id, conn := range s.conns {55 delete(s.conns, id)56 if err := conn.Close(); err != nil {57 s.Logger.Error("Error closing connection", "id", id, "conn", conn, "err", err)58 }59 }60}61func (s *SocketServer) addConn(conn net.Conn) int {62 s.connsMtx.Lock()63 defer s.connsMtx.Unlock()64 connID := s.nextConnID65 s.nextConnID++66 s.conns[connID] = conn67 return connID68}69// deletes conn even if close errs70func (s *SocketServer) rmConn(connID int) error {71 s.connsMtx.Lock()72 defer s.connsMtx.Unlock()73 conn, ok := s.conns[connID]74 if !ok {75 return fmt.Errorf("Connection %d does not exist", connID)76 }77 delete(s.conns, connID)78 return conn.Close()79}80func (s *SocketServer) acceptConnectionsRoutine() {81 for {82 // Accept a connection83 s.Logger.Info("Waiting for new connection...")84 conn, err := s.listener.Accept()85 if err != nil {86 if !s.IsRunning() {87 return // Ignore error from listener closing.88 }89 s.Logger.Error("Failed to accept connection: " + err.Error())90 continue91 }92 s.Logger.Info("Accepted a new connection")93 connID := s.addConn(conn)94 closeConn := make(chan error, 2) // Push to signal connection closed95 responses := make(chan *types.Response, 1000) // A channel to buffer responses96 // Read requests from conn and deal with them97 go s.handleRequests(closeConn, conn, responses)98 // Pull responses from 'responses' and write them to conn.99 go s.handleResponses(closeConn, conn, responses)100 // Wait until signal to close connection101 go s.waitForClose(closeConn, connID)102 }103}104func (s *SocketServer) waitForClose(closeConn chan error, connID int) {105 err := <-closeConn106 if err == io.EOF {107 s.Logger.Error("Connection was closed by client")108 } else if err != nil {109 s.Logger.Error("Connection error", "error", err)110 } else {111 // never happens112 s.Logger.Error("Connection was closed.")113 }114 // Close the connection115 if err := s.rmConn(connID); err != nil {116 s.Logger.Error("Error in closing connection", "error", err)117 }118}119// Read requests from conn and deal with them120func (s *SocketServer) handleRequests(closeConn chan error, conn net.Conn, responses chan<- *types.Response) {121 var count int122 var bufReader = bufio.NewReader(conn)123 for {124 var req = &types.Request{}125 err := types.ReadMessage(bufReader, req)126 if err != nil {127 if err == io.EOF {128 closeConn <- err...
pool.go
Source:pool.go
...22 MaxIdle int23 //çæè¿æ¥çæ¹æ³24 Factory func() (interface{}, error)25 //å
³éè¿æ¥çæ¹æ³26 Close func(interface{}) error27 //æ£æ¥è¿æ¥æ¯å¦ææçæ¹æ³28 Ping func(interface{}) error29 //è¿æ¥æ大空é²æ¶é´ï¼è¶
è¿è¯¥äºä»¶åå°å¤±æ30 IdleTimeout time.Duration31}32// channelPool åæ¾è¿æ¥ä¿¡æ¯33type channelPool struct {34 mu sync.RWMutex35 conns chan *idleConn36 factory func() (interface{}, error)37 close func(interface{}) error38 ping func(interface{}) error39 idleTimeout, waitTimeOut time.Duration40 maxActive int41 openingConns int42}43type idleConn struct {44 conn interface{}45 t time.Time46}47var (48 //ErrClosed è¿æ¥æ± å·²ç»å
³éError49 ErrClosed = errors.New("pool is closed")50)51// Pool åºæ¬æ¹æ³52type Pool interface {53 Get() (interface{}, error)54 Put(interface{}) error55 Close(interface{}) error56 Release()57 Len() int58}59// NewChannelPool åå§åè¿æ¥60func NewChannelPool(poolConfig *Config) (Pool, error) {61 if !(poolConfig.InitialCap <= poolConfig.MaxIdle && poolConfig.MaxCap >= poolConfig.MaxIdle && poolConfig.InitialCap >= 0) {62 return nil, errors.New("invalid capacity settings")63 }64 if poolConfig.Factory == nil {65 return nil, errors.New("invalid factory func settings")66 }67 if poolConfig.Close == nil {68 return nil, errors.New("invalid close func settings")69 }70 c := &channelPool{71 conns: make(chan *idleConn, poolConfig.MaxIdle),72 factory: poolConfig.Factory,73 close: poolConfig.Close,74 idleTimeout: poolConfig.IdleTimeout,75 maxActive: poolConfig.MaxCap,76 openingConns: poolConfig.InitialCap,77 }78 if poolConfig.Ping != nil {79 c.ping = poolConfig.Ping80 }81 for i := 0; i < poolConfig.InitialCap; i++ {82 conn, err := c.factory()83 if err != nil {84 c.Release()85 return nil, fmt.Errorf("factory is not able to fill the pool: %s", err)86 }87 c.conns <- &idleConn{conn: conn, t: time.Now()}88 }89 return c, nil90}91// getConns è·åææè¿æ¥92func (c *channelPool) getConns() chan *idleConn {93 c.mu.Lock()94 conns := c.conns95 c.mu.Unlock()96 return conns97}98// Get ä»poolä¸åä¸ä¸ªè¿æ¥99func (c *channelPool) Get() (interface{}, error) {100 conns := c.getConns()101 if conns == nil {102 return nil, ErrClosed103 }104 for {105 select {106 case wrapConn := <-conns:107 if wrapConn == nil {108 return nil, ErrClosed109 }110 //å¤ææ¯å¦è¶
æ¶ï¼è¶
æ¶å丢å¼111 if timeout := c.idleTimeout; timeout > 0 {112 if wrapConn.t.Add(timeout).Before(time.Now()) {113 //丢å¼å¹¶å
³é该è¿æ¥114 c.Close(wrapConn.conn)115 continue116 }117 }118 //å¤ææ¯å¦å¤±æï¼å¤±æå丢å¼ï¼å¦æç¨æ·æ²¡æè®¾å® ping æ¹æ³ï¼å°±ä¸æ£æ¥119 if c.ping != nil {120 if err := c.Ping(wrapConn.conn); err != nil {121 c.Close(wrapConn.conn)122 continue123 }124 }125 return wrapConn.conn, nil126 default:127 c.mu.Lock()128 defer c.mu.Unlock()129 if c.openingConns >= c.maxActive {130 return nil, ErrMaxActiveConnReached131 }132 if c.factory == nil {133 return nil, ErrClosed134 }135 conn, err := c.factory()136 if err != nil {137 return nil, err138 }139 c.openingConns++140 return conn, nil141 }142 }143}144// Put å°è¿æ¥æ¾åpoolä¸145func (c *channelPool) Put(conn interface{}) error {146 if conn == nil {147 return errors.New("connection is nil. rejecting")148 }149 c.mu.Lock()150 if c.conns == nil {151 c.mu.Unlock()152 return c.Close(conn)153 }154 select {155 case c.conns <- &idleConn{conn: conn, t: time.Now()}:156 c.mu.Unlock()157 return nil158 default:159 c.mu.Unlock()160 //è¿æ¥æ± 已满ï¼ç´æ¥å
³é该è¿æ¥161 return c.Close(conn)162 }163}164// Close å
³éåæ¡è¿æ¥165func (c *channelPool) Close(conn interface{}) error {166 if conn == nil {167 return errors.New("connection is nil. rejecting")168 }169 c.mu.Lock()170 defer c.mu.Unlock()171 if c.close == nil {172 return nil173 }174 c.openingConns--175 return c.close(conn)176}177// Ping æ£æ¥åæ¡è¿æ¥æ¯å¦ææ178func (c *channelPool) Ping(conn interface{}) error {179 if conn == nil {...
redis.go
Source:redis.go
...30 return nil, err31 }32 if len(password) > 0 {33 if _, err := c.Do("AUTH", password); err != nil {34 c.Close()35 return nil, err36 }37 }38 if _, err := c.Do("select", database); err != nil {39 c.Close()40 return nil, err41 }42 return c, err43 },44 TestOnBorrow: func(c redis.Conn, t time.Time) error {45 _, err := c.Do("PING")46 return err47 },48 }49 if _, err := r.Do("PING"); err != nil {50 log.Panicln("Init redis pool failed.", err.Error())51 }52 return r53}54// GetConn pool55func (p *ConnPool) GetConn() redis.Conn {56 conn := p.Pool.Get()57 if conn.Err() != nil {58 log.Printf("GetConn redis fail, %v", conn.Err())59 time.Sleep(1)60 for {61 // ç´å°è·åæå62 conn = p.Pool.Get()63 if conn.Err() == nil {64 break65 }66 }67 }68 return conn69}70// Close pool71func (p *ConnPool) Close() error {72 err := p.Pool.Close()73 return err74}75// Do commands76func (p *ConnPool) Do(command string, args ...interface{}) (interface{}, error) {77 conn := p.GetConn()78 defer conn.Close()79 return conn.Do(command, args...)80}81// Set for value82func (p *ConnPool) Set(key string, value interface{}) (interface{}, error) {83 conn := p.GetConn()84 defer conn.Close()85 return conn.Do("SET", key, value)86}87// SetEx 设置带æææçvalue88func (p *ConnPool) SetEx(key string, seconds int64, value interface{}) (interface{}, error) {89 conn := p.GetConn()90 defer conn.Close()91 return conn.Do("SETEX", key, seconds, value)92}93// GetString for string94func (p *ConnPool) GetString(key string) (string, error) {95 conn := p.GetConn()96 defer conn.Close()97 return redis.String(conn.Do("GET", key))98}99// GetBytes for bytes100func (p *ConnPool) GetBytes(key string) ([]byte, error) {101 conn := p.GetConn()102 defer conn.Close()103 return redis.Bytes(conn.Do("GET", key))104}105// GetInt for int106func (p *ConnPool) GetInt(key string) (int, error) {107 conn := p.GetConn()108 defer conn.Close()109 return redis.Int(conn.Do("GET", key))110}111// GetInt64 for int64112func (p *ConnPool) GetInt64(key string) (int64, error) {113 conn := p.GetConn()114 defer conn.Close()115 return redis.Int64(conn.Do("GET", key))116}117// GetUint64 for uint64118func (p *ConnPool) GetUint64(key string) (uint64, error) {119 conn := p.GetConn()120 defer conn.Close()121 return redis.Uint64(conn.Do("GET", key))122}123// Del for key124func (p *ConnPool) Del(key string) (interface{}, error) {125 conn := p.GetConn()126 defer conn.Close()127 return conn.Do("DEL", key)128}129// Expire for key130func (p *ConnPool) Expire(key string, seconds int64) (interface{}, error) {131 conn := p.GetConn()132 defer conn.Close()133 return conn.Do("EXPIRE", key, seconds)134}135// Keys for key136func (p *ConnPool) Keys(pattern string) ([]string, error) {137 conn := p.GetConn()138 defer conn.Close()139 return redis.Strings(conn.Do("KEYS", pattern))140}141// KeysByteSlices for key142func (p *ConnPool) KeysByteSlices(pattern string) ([][]byte, error) {143 conn := p.GetConn()144 defer conn.Close()145 return redis.ByteSlices(conn.Do("KEYS", pattern))146}147// SetHashMap for hash map148func (p *ConnPool) SetHashMap(key string, fieldValue map[string]interface{}) (interface{}, error) {149 conn := p.GetConn()150 defer conn.Close()151 return conn.Do("HMSET", redis.Args{}.Add(key).AddFlat(fieldValue)...)152}153// GetHashMapString for hash map154func (p *ConnPool) GetHashMapString(key string) (map[string]string, error) {155 conn := p.GetConn()156 defer conn.Close()157 return redis.StringMap(conn.Do("HGETALL", key))158}159// GetHashMapInt for hash map160func (p *ConnPool) GetHashMapInt(key string) (map[string]int, error) {161 conn := p.GetConn()162 defer conn.Close()163 return redis.IntMap(conn.Do("HGETALL", key))164}165// GetHashMapInt64 for hash map166func (p *ConnPool) GetHashMapInt64(key string) (map[string]int64, error) {167 conn := p.GetConn()168 defer conn.Close()169 return redis.Int64Map(conn.Do("HGETALL", key))170}171// INCR å° key ä¸å¨åçæ°åå¼å¢ä¸ï¼å¦æ key ä¸åå¨ï¼é£ä¹ key çå¼ä¼å
被åå§å为 0 ï¼ç¶ååæ§è¡ INCR æä½ã172func (p *ConnPool) INCR(key string) (int, error) {173 conn := p.GetConn()174 defer conn.Close()175 return redis.Int(conn.Do("INCR", key))176}...
Close
Using AI Code Generation
1conn.Close()2conn.Close()3conn.Close()4conn.Close()5conn.Close()6conn.Close()7conn.Close()8conn.Close()9conn.Close()10conn.Close()11conn.Close()12conn.Close()13conn.Close()14conn.Close()15conn.Close()16conn.Close()17conn.Close()
Close
Using AI Code Generation
1conn.Close()2conn.Close()3conn.Close()4conn.Close()5conn.Close()6conn.Close()7conn.Close()8conn.Close()9conn.Close()10conn.Close()11conn.Close()12conn.Close()13conn.Close()14conn.Close()15conn.Close()16conn.Close()17conn.Close()18conn.Close()19conn.Close()20conn.Close()21conn.Close()22conn.Close()23conn.Close()24conn.Close()25conn.Close()26conn.Close()27conn.Close()28conn.Close()29conn.Close()30conn.Close()31conn.Close()
Close
Using AI Code Generation
1import (2func main() {3 fmt.Println(stringutil.Reverse("Hello, world!"))4}5import (6func main() {7 fmt.Println(stringutil.Reverse("Hello, world!"))8}9import (10func main() {11 fmt.Println(stringutil.Reverse("Hello, world!"))12}13import (14func main() {15 fmt.Println(stringutil.Reverse("Hello, world!"))16}17import (18func main() {19 fmt.Println(stringutil.Reverse("Hello, world!"))20}21import (22func main() {23 fmt.Println(stringutil.Reverse("Hello, world!"))
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!