3
0

import crm entry point

This commit is contained in:
Tit Petric 2018-07-01 01:46:37 +02:00
parent a7fcdf3795
commit a21de65eb4
3 changed files with 100 additions and 0 deletions

58
cmd/crm/main.go Normal file
View File

@ -0,0 +1,58 @@
package main
import (
"flag"
"log"
"net"
"os"
"net/http"
"github.com/go-chi/chi"
"github.com/titpetric/crust/crm"
"github.com/titpetric/factory"
)
func handleError(err error, message string) {
if message == "" {
message = "Error making API call"
}
if err != nil {
log.Fatalf(message+": %v", err.Error())
}
}
func main() {
// set up flags
var (
addr = flag.String("addr", ":3000", "Listen address for HTTP server")
)
flag.Parse()
// log to stdout not stderr
log.SetOutput(os.Stdout)
// set up database connection
factory.Database.Add("default", "crust:crust@tcp(db1:3306)/crust?collation=utf8mb4_general_ci")
/*
db, err := factory.Database.Get()
handleError(err, "Can't connect to database")
db.Profiler = &factory.Database.ProfilerStdout
*/
// listen socket for http server
log.Println("Starting http server on address " + *addr)
listener, err := net.Listen("tcp", *addr)
handleError(err, "Can't listen on addr "+*addr)
// route options
routeOptions, err := RouteOptions{}.New()
handleError(err, "Error creating RouteOptions object")
// mount routes
r := chi.NewRouter()
MountRoutes(r, routeOptions, crm.MountRoutes)
http.Serve(listener, r)
}

16
cmd/crm/options.go Normal file
View File

@ -0,0 +1,16 @@
package main
type RouteOptions struct {
enableLogging bool
}
func (RouteOptions) New() (*RouteOptions, error) {
opts := &RouteOptions{}
opts.enableLogging = true
return opts, nil
}
func (o *RouteOptions) EnableLogging(enable bool) *RouteOptions {
o.enableLogging = enable
return o
}

26
cmd/crm/routes.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
)
// MountRoutes will register API routes
func MountRoutes(r chi.Router, opts *RouteOptions, mountRoutes func(r chi.Router)) {
// CORS for local development...
cors := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
})
r.Use(cors.Handler)
if opts.enableLogging {
r.Use(middleware.Logger)
}
mountRoutes(r)
}