bottin-agenda/cmd/web.go

91 lines
2 KiB
Go
Raw Normal View History

package cmd
import (
"crypto/subtle"
"embed"
"fmt"
"html/template"
"io"
"log"
"git.agecem.com/agecem/bottin-agenda/data"
"git.agecem.com/agecem/bottin-agenda/models"
"git.agecem.com/agecem/bottin-agenda/web"
"git.agecem.com/agecem/bottin-agenda/web/webhandlers"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var templatesFS embed.FS
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
// webCmd represents the web command
var webCmd = &cobra.Command{
Use: "web",
Short: "Démarrer le client web",
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
var config models.Config
err := viper.Unmarshal(&config)
if err != nil {
log.Fatalf("Error during webCmd#viper.Unmarshal(): %s", err)
}
// Ping API server
apiClient := data.NewApiClient(config.Web.Api.Key, config.Web.Api.Host, config.Web.Api.Protocol, config.Web.Api.Port)
healthResult, err := apiClient.GetHealth()
if err != nil {
log.Fatalf("Error during webCmd#apiClient.GetHealth(): %s", err)
}
log.Println(healthResult)
e := echo.New()
// Middlewares
e.Pre(middleware.AddTrailingSlash())
e.Use(middleware.BasicAuth(func(user, password string, c echo.Context) (bool, error) {
usersMatch := subtle.ConstantTimeCompare([]byte(user), []byte(config.Web.User)) == 1
passwordsMatch := subtle.ConstantTimeCompare([]byte(password), []byte(config.Web.Password)) == 1
return usersMatch && passwordsMatch, nil
}))
// Template
t := &Template{
templates: template.Must(template.ParseFS(templatesFS, "templates/*.html")),
}
e.Renderer = t
// Routes
e.GET("/", webhandlers.GetIndex)
//e.POST("/transaction", webhandlers.PostTransaction)
// Execution
e.Logger.Fatal(e.Start(
fmt.Sprintf(":%d", config.Web.Port)))
},
}
func init() {
rootCmd.AddCommand(webCmd)
templatesFS = web.GetTemplates()
}