github.com/pawelgaczynski/gain@v0.4.0-alpha.0.20230821120126-41f1e60a18da/gain.go (about) 1 // Copyright (c) 2023 Paweł Gaczyński 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 //nolint:revive 16 package gain 17 18 import ( 19 "github.com/pkg/errors" 20 ) 21 22 type EventHandler interface { 23 // OnStart fires when the server is ready for accepting new connections. 24 OnStart(server Server) 25 // OnAccept fires when a new TCP connection has been opened (will not be fired for UDP protocol). 26 // This is good place to set the socket options, such as TCP keepalive. 27 // The incoming data buffer of the connection will be empty, 28 // so the attempt to read the data will never succeed, but you can perform a write at this point 29 // The Conn c has information about the connection such as it's local and remote address. 30 OnAccept(c Conn) 31 // OnRead fires when a socket receives n bytes of data from the peer. 32 // 33 // Call c.Read() of Conn c to read incoming data from the peer. call c.Write() to send data to the remote peer. 34 OnRead(c Conn, n int) 35 // OnWrite fires right after a n bytes is written to the peer socket. 36 OnWrite(c Conn, n int) 37 // OnClose fires when a TCP connection has been closed (will not be fired for UDP protocol). 38 // The parameter err is the last known connection error. 39 OnClose(c Conn, err error) 40 } 41 42 // DefaultEventHandler is a default implementation for all of the EventHandler callbacks (do nothing). 43 // Compose it with your own implementation of EventHandler and you won't need to implement all callbacks. 44 type DefaultEventHandler struct{} 45 46 func (e DefaultEventHandler) OnStart(server Server) {} 47 func (e DefaultEventHandler) OnAccept(c Conn) {} 48 func (e DefaultEventHandler) OnClose(c Conn, err error) {} 49 func (e DefaultEventHandler) OnRead(c Conn, n int) {} 50 func (e DefaultEventHandler) OnWrite(c Conn, n int) {} 51 52 // ListenAndServe starts a server with a given address and event handler. 53 // The server can be configured with additional options. 54 func ListenAndServe(address string, eventHandler EventHandler, options ...ConfigOption) error { 55 server := NewServer(eventHandler, NewConfig(options...)) 56 57 return errors.Wrapf(server.Start(address), "starting server error") 58 }