1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- package myth
- import (
- "context"
- "fmt"
- "log"
- "net/http"
- "os"
- "os/signal"
- "syscall"
- "time"
- //"golang.org/x/net/http2"
- )
- var (
- readTimeout = 30 * time.Second
- readHeaderTimeout = 30 * time.Second
- writeTimeout = 30 * time.Second
- idleTimeout = 30 * time.Second
- shutTimeout = 30 * time.Second
- )
- func newServe(addr string, router http.Handler) *http.Server {
- return &http.Server{
- Addr: addr,
- Handler: router,
- ReadTimeout: readTimeout,
- ReadHeaderTimeout: readHeaderTimeout,
- WriteTimeout: writeTimeout,
- IdleTimeout: idleTimeout,
- MaxHeaderBytes: MB,
- }
- }
- func run(useV2 bool, addr, certFile, keyFile string, router http.Handler) {
- s := newServe(addr, router)
- /*
- if useV2 {
- http2.VerboseLogs = false
- http2.ConfigureServer(s, nil)
- }
- // */
- errc := make(chan error)
- go func() {
- c := make(chan os.Signal, 1)
- signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
- errc <- fmt.Errorf("%s", <-c)
- }()
- go func() {
- var e error
- log.Println("HTTP Server listen on", addr)
- if len(certFile) > 0 && len(keyFile) > 0 {
- e = s.ListenAndServeTLS(certFile, keyFile)
- } else {
- e = s.ListenAndServe()
- }
- log.Println("Exit HTTP server", "Quit", e)
- }()
- e := <-errc
- log.Println("Recvie", e)
- ctx, cancel := context.WithTimeout(context.Background(), shutTimeout)
- defer cancel()
- s.Shutdown(ctx)
- log.Println("Exit HTTP server")
- }
- // ListenAndServe new server and start
- func ListenAndServe(addr string, router http.Handler) {
- run(false, addr, ``, ``, router)
- }
- // ListenAndServeTLS new server and start
- func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler) {
- run(false, addr, certFile, keyFile, router)
- }
- // ListenAndServeV2 new http2 server and start
- func ListenAndServeV2(addr string, router http.Handler) {
- run(true, addr, ``, ``, router)
- }
- // ListenAndServeTLSV2 new http2 server and start
- func ListenAndServeTLSV2(addr, certFile, keyFile string, router http.Handler) {
- run(true, addr, certFile, keyFile, router)
- }
|