github.com/m3db/m3@v1.5.0/src/dbnode/network/server/httpjson/node/server.go (about) 1 // Copyright (c) 2016 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package node 22 23 import ( 24 "net" 25 "net/http" 26 27 "github.com/m3db/m3/src/dbnode/generated/thrift/rpc" 28 ns "github.com/m3db/m3/src/dbnode/network/server" 29 "github.com/m3db/m3/src/dbnode/network/server/httpjson" 30 "github.com/m3db/m3/src/x/context" 31 ) 32 33 type server struct { 34 address string 35 service rpc.TChanNode 36 opts httpjson.ServerOptions 37 } 38 39 // NewServer creates a node HTTP network service 40 func NewServer( 41 service rpc.TChanNode, 42 address string, 43 contextPool context.Pool, 44 opts httpjson.ServerOptions, 45 ) ns.NetworkService { 46 if opts == nil { 47 opts = httpjson.NewServerOptions() 48 } 49 opts = opts. 50 SetContextFn(httpjson.NewDefaultContextFn(contextPool)). 51 SetPostResponseFn(httpjson.DefaulPostResponseFn) 52 return &server{ 53 address: address, 54 service: service, 55 opts: opts, 56 } 57 } 58 59 func (s *server) ListenAndServe() (ns.Close, error) { 60 mux := http.NewServeMux() 61 if err := httpjson.RegisterHandlers(mux, s.service, s.opts); err != nil { 62 return nil, err 63 } 64 65 listener, err := net.Listen("tcp", s.address) 66 if err != nil { 67 return nil, err 68 } 69 70 server := http.Server{ 71 Handler: mux, 72 ReadTimeout: s.opts.ReadTimeout(), 73 WriteTimeout: s.opts.WriteTimeout(), 74 } 75 76 go func() { 77 server.Serve(listener) 78 }() 79 80 return func() { 81 listener.Close() 82 }, nil 83 }