github.com/vlifesystems/rulehunter@v0.0.0-20180501090014-673078aa4a83/cmd/httpserver.go (about) 1 // Copyright (C) 2018 vLife Systems Ltd <http://vlifesystems.com> 2 // Licensed under an MIT licence. Please see LICENSE.md for details. 3 4 package cmd 5 6 import ( 7 "context" 8 "fmt" 9 "net/http" 10 11 "github.com/vlifesystems/rulehunter/logger" 12 "github.com/vlifesystems/rulehunter/quitter" 13 ) 14 15 func httpServer( 16 port int, 17 wwwDir string, 18 q *quitter.Quitter, 19 l logger.Logger, 20 ) { 21 if port <= 0 { 22 return 23 } 24 q.Add() 25 defer q.Done() 26 shutdownSent := false 27 srv := &http.Server{Addr: fmt.Sprintf(":%d", port)} 28 http.Handle("/", http.FileServer(http.Dir(wwwDir))) 29 l.Info(fmt.Sprintf("Starting http server on port: %d", port)) 30 go func() { 31 if err := srv.ListenAndServe(); err != nil { 32 if !shutdownSent { 33 l.Error(fmt.Errorf("http server: %s", err)) 34 } 35 } 36 }() 37 38 // Wait until Quit is sent on channel 39 <-q.C 40 shutdownSent = true 41 if err := srv.Shutdown(context.Background()); err != nil { 42 l.Error(fmt.Errorf("http server: %s", err)) 43 } else { 44 l.Info(fmt.Sprintf("Shutdown http server on port: %d", port)) 45 } 46 }