github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/graceful/server_http.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package graceful
     7  
     8  import (
     9  	"context"
    10  	"crypto/tls"
    11  	"net"
    12  	"net/http"
    13  
    14  	"golang.org/x/net/http2"
    15  	"golang.org/x/net/http2/h2c"
    16  )
    17  
    18  func newHTTPServer(network, address, name string, handler http.Handler) (*Server, ServeFunction) {
    19  	server := NewServer(network, address, name)
    20  	httpServer := http.Server{
    21  		ReadTimeout:    DefaultReadTimeOut,
    22  		WriteTimeout:   DefaultWriteTimeOut,
    23  		MaxHeaderBytes: DefaultMaxHeaderBytes,
    24  		Handler:        h2c.NewHandler(handler, &http2.Server{}),
    25  		BaseContext:    func(net.Listener) context.Context { return GetManager().HammerContext() },
    26  	}
    27  	server.OnShutdown = func() {
    28  		httpServer.SetKeepAlivesEnabled(false)
    29  	}
    30  	return server, httpServer.Serve
    31  }
    32  
    33  // HTTPListenAndServe listens on the provided network address and then calls Serve
    34  // to handle requests on incoming connections.
    35  func HTTPListenAndServe(network, address, name string, handler http.Handler) error {
    36  	server, lHandler := newHTTPServer(network, address, name, handler)
    37  	return server.ListenAndServe(lHandler)
    38  }
    39  
    40  // HTTPListenAndServeTLSConfig listens on the provided network address and then calls Serve
    41  // to handle requests on incoming connections.
    42  func HTTPListenAndServeTLSConfig(network, address, name string, tlsConfig *tls.Config, handler http.Handler) error {
    43  	server, lHandler := newHTTPServer(network, address, name, handler)
    44  	return server.ListenAndServeTLSConfig(tlsConfig, lHandler)
    45  }