servercmd

package
v0.104.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 19, 2024 License: GPL-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Copyright © 2023 The Haul Authors

Copyright © 2024 The Haul Authors

Index

Constants

This section is empty.

Variables

View Source
var ServerCmd = &cobra.Command{
	Use:   "server",
	Short: "Start the API server",
	Long: `Start the API server or import/export the database

	See subcommands for database manipulations that skip the API server.`,
	Args: cobra.ExactArgs(0),
	Run: func(cmd *cobra.Command, args []string) {
		cfg, err := config.Unmarshal()
		if err != nil {
			log.Fatalf("Error during ServerCmd's config.Unmarshal(): %s", err)
		}

		postgresClient, err := dbclient.NewPostgresClientFromViper()
		if err != nil {
			log.Fatalf("Error during ServerCmd's dbclient.NewPostgresClientFromViper(): %s", err)
		}
		defer postgresClient.DB.Close()

		if err := postgresClient.DB.Ping(); err != nil {
			log.Fatalf("Error during ServerCmd's postgresClient.DB.Ping(): %s", err)
		} else {
			log.Println("[haul db] Postgres database ok")
		}

		if _, err := postgresClient.Seed(); err != nil {
			log.Println("[haul db] Seed returned error:", err.Error())
		}

		client := http.DefaultClient

		apiClient, err := apiclient.NewFromViper(client)
		if err != nil {
			log.Fatalf("Error during ServerCmd's dbclient.NewPostgresClientFromViper(): %s", err)
		}

		e := echo.New()

		e.Pre(middleware.AddTrailingSlash())

		if cfg.Server.Api.Key != "" {
			e.Use(middleware.KeyAuth(func(key string, c echo.Context) (bool, error) {
				return subtle.ConstantTimeCompare([]byte(key), []byte(cfg.Server.Api.Key)) == 1, nil
			}))
		}

		prefix := "/v1"
		v1 := e.Group(prefix)

		p := pave.New()

		apiHandler := apihandler.NewWithPave(apiClient, postgresClient, &p)

		apihandler.Declare(v1, apiHandler, prefix)

		switch cfg.Server.Api.TLS.Enabled {
		case true:
			if cfg.Server.Api.TLS.Cert == "" {
				log.Fatal("API server TLS enabled, but no certificate file was provided.")
			}
			if cfg.Server.Api.TLS.Key == "" {
				log.Fatal("API server TLS enabled, but no private key file was provided.")
			}

			e.Logger.Fatal(e.StartTLS(fmt.Sprintf(":%d", cfg.Server.Api.Port), cfg.Server.Api.TLS.Cert, cfg.Server.Api.TLS.Key))
		case false:
			e.Logger.Fatal(e.Start(fmt.Sprintf(":%d", cfg.Server.Api.Port)))
		}

	},
}

ServerCmd represents the server command

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL