73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
package cmd
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"gis/app"
|
|
"gis/server"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// serveCmd represents the serve command
|
|
var serveCmd = &cobra.Command{
|
|
Use: "serve",
|
|
Short: "Serve HTTP server",
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
application := app.NewApp(cmd.Context())
|
|
|
|
srv := &http.Server{
|
|
Addr: fmt.Sprintf(":%d", application.Cfg.Port),
|
|
Handler: server.AppRouter(application),
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
ReadTimeout: 120 * time.Second,
|
|
WriteTimeout: 120 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
}
|
|
|
|
idleClosed := make(chan struct{})
|
|
|
|
go func() {
|
|
sigint := make(chan os.Signal, 1)
|
|
signal.Notify(sigint, os.Interrupt, syscall.SIGTERM)
|
|
<-sigint
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
|
|
if err := srv.Shutdown(ctx); err != nil {
|
|
log.Printf("shutdown server error: %v", err)
|
|
}
|
|
|
|
close(idleClosed)
|
|
}()
|
|
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatalf("listen: %s\n", err)
|
|
}
|
|
|
|
<-idleClosed
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
rootCmd.AddCommand(serveCmd)
|
|
|
|
// Here you will define your flags and configuration settings.
|
|
|
|
// Cobra supports Persistent Flags which will work for this command
|
|
// and all subcommands, e.g.:
|
|
// serveCmd.PersistentFlags().String("foo", "", "A help for foo")
|
|
|
|
// Cobra supports local flags which will only run when this command
|
|
// is called directly, e.g.:
|
|
// serveCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
|
}
|