app.go 1.68 KB
package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"

	_ "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
	router *mux.Router
}

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

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s", config.Database.User, config.Database.Password, config.Database.Host, config.Database.Name)
	app.db = sqlx.MustOpen("mysql", dsn)

	app.router = mux.NewRouter()
	app.router.HandleFunc("/users", app.PostUsers).Methods("POST")
	app.router.HandleFunc("/users/tokens", app.PostTokens).Methods("POST")
	app.router.Handle("/extractions", app.WithAuth(app.PostExtractions)).Methods("Post")
	app.router.HandleFunc("/extractions/{file}/calls", app.GetCalls).Methods("GET")
	app.router.HandleFunc("/extractions/{file}/messages", app.GetMessages).Methods("GET")
	app.router.HandleFunc("/extractions/{file}/calls/analyses", app.GetCallsAnalyses).Methods("GET")
	app.router.HandleFunc("/extractions/{file}/apps/analyses", app.GetAppsAnalyses).Methods("GET")
	app.router.HandleFunc("/extractions/{file}/messages/analyses", app.GetMessagesAnalyses).Methods("GET")
	app.router.HandleFunc("/extractions/{file}/processes", app.GetProcesses).Methods("GET")
	app.router.HandleFunc("/extractions/{file}/alarms", app.GetAlarms).Methods("GET")

	return app
}

func (app *App) Serve() {
	http.ListenAndServe(fmt.Sprintf(":%d", app.Config.Port), handlers.CORS(
		handlers.AllowedMethods([]string{"GET", "POST", "UPDATE", "DELETE"}),
		handlers.AllowedOrigins([]string{"*"}),
	)(app.router))
}