app.go 2.47 KB
package main

import (
	"fmt"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/olivere/elastic/v7"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

type Prop int

const (
	PropUserNo Prop = iota
)

type App struct {
	Config Config
	db     *sqlx.DB
	es     *elastic.Client
	echo   *echo.Echo
}

func NewApp(config Config) *App {
	app := new(App)
	app.Config = config

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true", config.Database.User, config.Database.Password, config.Database.Host, config.Database.Name)
	app.db = sqlx.MustOpen("mysql", dsn)
	es, err := elastic.NewClient()
	if err != nil {
		panic(err)
	}
	app.es = es

	auth := middleware.JWTWithConfig(middleware.JWTConfig{
		SigningKey: []byte(config.TokenSecret),
		Claims:     &AuthClaims{},
	})

	app.echo = echo.New()

	app.echo.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowMethods: []string{
			http.MethodGet,
			http.MethodPost,
			http.MethodPut,
			http.MethodDelete,
			http.MethodPatch,
			http.MethodOptions,
			http.MethodHead,
		},
		AllowHeaders: []string{"*"},
	}))

	app.echo.POST("/users", app.PostUsers)
	app.echo.POST("/users/tokens", app.PostTokens)
	app.echo.GET("/extractions", app.GetExtractions, auth)
	app.echo.POST("/extractions", app.PostExtractions, auth)

	extraction := app.echo.Group("/extractions/:no")

	extraction.GET("/calls", app.GetCalls)
	extraction.POST("/calls", app.PostCall)
	extraction.PUT("/calls/:id", app.PutCall)
	extraction.DELETE("/calls/:id", app.DeleteCall)

	extraction.GET("/messages", app.GetMessages)
	extraction.POST("/messages", app.PostMessage)
	extraction.PUT("/messages/:id", app.PutMessage)
	extraction.DELETE("/messages/:id", app.DeleteMessage)

	extraction.GET("/calls/analyses", app.GetCallsAnalyses)
	extraction.GET("/regions", app.GetRegions)

	extraction.GET("/apps/analyses", app.GetAppsAnalyses)
	extraction.POST("/apps/analyses", app.PostAppAnalysis)
	extraction.PUT("/apps/analyses/:package", app.PutAppAnalysis)
	extraction.DELETE("/apps/analyses/:package", app.DeleteAppAnalysis)

	extraction.GET("/messages/analyses", app.GetMessagesAnalyses)
	extraction.GET("/processes", app.GetProcesses)
	extraction.GET("/alarms", app.GetAlarms)
	extraction.GET("/schedules", app.GetSchedules)
	extraction.GET("/dailies", app.GetDailyContacts)

	app.echo.GET("/graph/:extractions", app.GetGraph)

	return app
}

func (app *App) Serve() {
	app.echo.Logger.Fatal(app.echo.Start(fmt.Sprintf(":%d", app.Config.Port)))
}