code.vegaprotocol.io/vega@v0.79.0/blockexplorer/api/gateway.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package api 17 18 import ( 19 "context" 20 "net" 21 "net/http" 22 "time" 23 24 libhttp "code.vegaprotocol.io/vega/libs/http" 25 "code.vegaprotocol.io/vega/logging" 26 27 "github.com/rs/cors" 28 ) 29 30 type Gateway struct { 31 GatewayConfig 32 httpServerMux *http.ServeMux 33 log *logging.Logger 34 srv *http.Server 35 lis net.Listener 36 } 37 38 type GatewayHandler interface { 39 http.Handler 40 Name() string 41 } 42 43 func NewGateway(log *logging.Logger, config GatewayConfig, lis net.Listener) *Gateway { 44 log = log.Named(gatewayNamedLogger) 45 return &Gateway{ 46 GatewayConfig: config, 47 httpServerMux: http.NewServeMux(), 48 log: log, 49 lis: lis, 50 } 51 } 52 53 func (s *Gateway) Register(handler GatewayHandler, endpoint string) { 54 s.log.Info("Registering with API gateway", logging.String("endpoint", endpoint), logging.String("handler", handler.Name())) 55 s.httpServerMux.Handle(endpoint+"/", http.StripPrefix(endpoint, handler)) 56 } 57 58 func (s *Gateway) Serve() error { 59 s.log.Info("Starting gateway", logging.String("address", s.lis.Addr().String())) 60 corsOptions := libhttp.CORSOptions(s.CORS) 61 handler := cors.New(corsOptions).Handler(s.httpServerMux) 62 srv := &http.Server{Handler: handler} 63 s.srv = srv 64 return s.srv.Serve(s.lis) 65 } 66 67 func (s *Gateway) Stop() { 68 if s.srv != nil { 69 s.log.Info("Stopping gateway", logging.String("address", s.lis.Addr().String())) 70 ctxWithTimeout, cancelFunc := context.WithTimeout(context.Background(), 15*time.Second) 71 defer cancelFunc() 72 _ = s.srv.Shutdown(ctxWithTimeout) 73 } 74 }