Debian Codegraph @

server/runner_http.go

raw
1 /*
2 Copyright 2013-2014 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 package server
18
19 import (
20 "crypto/tls"
21 "net"
22 "net/http"
23 "golang.org/x/net/netutil"
24
25 "gitlab.com/ubports/development/core/lomiri-push-service/config"
26 )
27
28 // A HTTPServeParsedConfig holds and can be used to parse the HTTP server config.
29 type HTTPServeParsedConfig struct {
30 ParsedHTTPAddr config.ConfigHostPort `json:"http_addr"`
31 ParsedHTTPReadTimeout config.ConfigTimeDuration `json:"http_read_timeout"`
32 ParsedHTTPWriteTimeout config.ConfigTimeDuration `json:"http_write_timeout"`
33 }
34
35 // HTTPServeRunner returns a function to serve HTTP requests.
36 // If httpLst is not nil it will be used as the underlying listener.
37 // If tlsCfg is not nit server over TLS with the config.
38 func HTTPServeRunner(httpLst net.Listener, h http.Handler, parsedCfg *HTTPServeParsedConfig, tlsCfg *tls.Config) func() {
39 if httpLst == nil {
40 var err error
41 httpLst, err = net.Listen("tcp", parsedCfg.ParsedHTTPAddr.HostPort())
42 if err != nil {
43 BootLogFatalf("start http listening: %v", err)
44 }
45 httpLst = netutil.LimitListener(httpLst, 2000)
46 }
47 BootLogListener("http", httpLst)
48 srv := &http.Server{
49 Handler: h,
50 ReadTimeout: parsedCfg.ParsedHTTPReadTimeout.TimeDuration(),
51 WriteTimeout: parsedCfg.ParsedHTTPWriteTimeout.TimeDuration(),
52 }
53 if tlsCfg != nil {
54 httpLst = tls.NewListener(httpLst, tlsCfg)
55 httpLst = netutil.LimitListener(httpLst, 1000)
56 }
57 return func() {
58 err := srv.Serve(httpLst)
59 if err != nil {
60 BootLogFatalf("accepting http connections: %v", err)
61 }
62 }
63 }