GoAsWebServer/main.go

67 lines
1.5 KiB
Go

package main
import (
"context"
"endmove/webserverlearning/api"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"time"
)
func main() {
// define graceful time for webserver shutdown - not required
var wait time.Duration
flag.DurationVar(&wait, "graceful-timeout", time.Second*30, "The time needed to close the connections")
flag.Parse() // apply flags <!> one shot function
// Config webserver
webserver := http.Server{
Addr: ":8080",
// Timeout (stop overloading and attack)
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
// Mux instance
Handler: api.NewServer(),
}
// Start webserver in routine
go func() {
if err := webserver.ListenAndServe(); err != nil {
fmt.Println(err.Error())
}
}()
fmt.Println("Server started on : http://localhost:8080")
// setuping sig to catch ctrl+c and throw a graceful stop
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
// waiting sig
<-sig
// defining graceful timeout
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
// shut down webserver with countdown
webserver.Shutdown(ctx)
fmt.Println("program has stopped")
os.Exit(0)
}
// func main() {
// http.HandleFunc("/hello-world", func(w http.ResponseWriter, r *http.Request) {
// w.Write([]byte("<h1>Hello World !</h1>"))
// })
// go http.ListenAndServe(":8080", nil)
// fmt.Println("Server listening on port :8080 at http://localhost:8080")
// time.Sleep(1 * time.Minute)
// fmt.Println("Quit...")
// }