1
0
mirror of https://github.com/raseels-repos/golang-saas-starter-kit.git synced 2025-06-15 00:15:15 +02:00
This commit is contained in:
Lee Brown
2019-05-23 14:32:24 -05:00
parent 271bf37c5d
commit c77dd8f5f3
25 changed files with 133 additions and 1284 deletions

View File

@ -4,27 +4,21 @@ import (
"context"
"net/http"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/db"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/web"
"go.opencensus.io/trace"
"github.com/jmoiron/sqlx"
)
// Check provides support for orchestration health checks.
type Check struct {
MasterDB *db.DB
MasterDB *sqlx.DB
// ADD OTHER STATE LIKE THE LOGGER IF NEEDED.
}
// Health validates the service is healthy and ready to accept requests.
func (c *Check) Health(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Check.Health")
defer span.End()
dbConn := c.MasterDB.Copy()
defer dbConn.Close()
if err := dbConn.StatusCheck(ctx); err != nil {
_, err := c.MasterDB.Exec("SELECT 1")
if err != nil {
return err
}
@ -34,5 +28,5 @@ func (c *Check) Health(ctx context.Context, w http.ResponseWriter, r *http.Reque
Status: "ok",
}
return web.Respond(ctx, w, status, http.StatusOK)
return web.RespondJson(ctx, w, status, http.StatusOK)
}

View File

@ -4,45 +4,32 @@ import (
"context"
"net/http"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/db"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/web"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/project"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"go.opencensus.io/trace"
)
// Project represents the Project API method handler set.
type Project struct {
MasterDB *db.DB
MasterDB *sqlx.DB
// ADD OTHER STATE LIKE THE LOGGER IF NEEDED.
}
// List returns all the existing projects in the system.
func (p *Project) List(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Project.List")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
projects, err := project.List(ctx, dbConn)
projects, err := project.List(ctx, p.MasterDB)
if err != nil {
return err
}
return web.Respond(ctx, w, projects, http.StatusOK)
return web.RespondJson(ctx, w, projects, http.StatusOK)
}
// Retrieve returns the specified project from the system.
func (p *Project) Retrieve(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Project.Retrieve")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
prod, err := project.Retrieve(ctx, dbConn, params["id"])
prod, err := project.Retrieve(ctx, p.MasterDB, params["id"])
if err != nil {
switch err {
case project.ErrInvalidID:
@ -54,17 +41,11 @@ func (p *Project) Retrieve(ctx context.Context, w http.ResponseWriter, r *http.R
}
}
return web.Respond(ctx, w, prod, http.StatusOK)
return web.RespondJson(ctx, w, prod, http.StatusOK)
}
// Create inserts a new project into the system.
func (p *Project) Create(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Project.Create")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.NewShutdownError("web value missing from context")
@ -75,22 +56,16 @@ func (p *Project) Create(ctx context.Context, w http.ResponseWriter, r *http.Req
return errors.Wrap(err, "")
}
nUsr, err := project.Create(ctx, dbConn, &np, v.Now)
nUsr, err := project.Create(ctx, p.MasterDB, &np, v.Now)
if err != nil {
return errors.Wrapf(err, "Project: %+v", &np)
}
return web.Respond(ctx, w, nUsr, http.StatusCreated)
return web.RespondJson(ctx, w, nUsr, http.StatusCreated)
}
// Update updates the specified project in the system.
func (p *Project) Update(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Project.Update")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.NewShutdownError("web value missing from context")
@ -101,7 +76,7 @@ func (p *Project) Update(ctx context.Context, w http.ResponseWriter, r *http.Req
return errors.Wrap(err, "")
}
err := project.Update(ctx, dbConn, params["id"], up, v.Now)
err := project.Update(ctx, p.MasterDB, params["id"], up, v.Now)
if err != nil {
switch err {
case project.ErrInvalidID:
@ -113,18 +88,12 @@ func (p *Project) Update(ctx context.Context, w http.ResponseWriter, r *http.Req
}
}
return web.Respond(ctx, w, nil, http.StatusNoContent)
return web.RespondJson(ctx, w, nil, http.StatusNoContent)
}
// Delete removes the specified project from the system.
func (p *Project) Delete(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Project.Delete")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
err := project.Delete(ctx, dbConn, params["id"])
err := project.Delete(ctx, p.MasterDB, params["id"])
if err != nil {
switch err {
case project.ErrInvalidID:
@ -136,5 +105,5 @@ func (p *Project) Delete(ctx context.Context, w http.ResponseWriter, r *http.Req
}
}
return web.Respond(ctx, w, nil, http.StatusNoContent)
return web.RespondJson(ctx, w, nil, http.StatusNoContent)
}

View File

@ -7,12 +7,12 @@ import (
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/mid"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/db"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/web"
"github.com/jmoiron/sqlx"
)
// API returns a handler for a set of routes.
func API(shutdown chan os.Signal, log *log.Logger, masterDB *db.DB, authenticator *auth.Authenticator) http.Handler {
func API(shutdown chan os.Signal, log *log.Logger, masterDB *sqlx.DB, authenticator *auth.Authenticator) http.Handler {
// Construct the web.App which holds all routes as well as common Middleware.
app := web.NewApp(shutdown, log, mid.Logger(log), mid.Errors(log), mid.Metrics(), mid.Panics())

View File

@ -5,16 +5,15 @@ import (
"net/http"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/db"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/web"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/user"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"go.opencensus.io/trace"
)
// User represents the User API method handler set.
type User struct {
MasterDB *db.DB
MasterDB *sqlx.DB
TokenGenerator user.TokenGenerator
// ADD OTHER STATE LIKE THE LOGGER AND CONFIG HERE.
@ -22,34 +21,22 @@ type User struct {
// List returns all the existing users in the system.
func (u *User) List(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.User.List")
defer span.End()
dbConn := u.MasterDB.Copy()
defer dbConn.Close()
usrs, err := user.List(ctx, dbConn)
usrs, err := user.List(ctx, u.MasterDB)
if err != nil {
return err
}
return web.Respond(ctx, w, usrs, http.StatusOK)
return web.RespondJson(ctx, w, usrs, http.StatusOK)
}
// Retrieve returns the specified user from the system.
func (u *User) Retrieve(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.User.Retrieve")
defer span.End()
dbConn := u.MasterDB.Copy()
defer dbConn.Close()
claims, ok := ctx.Value(auth.Key).(auth.Claims)
if !ok {
return errors.New("claims missing from context")
}
usr, err := user.Retrieve(ctx, claims, dbConn, params["id"])
usr, err := user.Retrieve(ctx, claims, u.MasterDB, params["id"])
if err != nil {
switch err {
case user.ErrInvalidID:
@ -63,17 +50,11 @@ func (u *User) Retrieve(ctx context.Context, w http.ResponseWriter, r *http.Requ
}
}
return web.Respond(ctx, w, usr, http.StatusOK)
return web.RespondJson(ctx, w, usr, http.StatusOK)
}
// Create inserts a new user into the system.
func (u *User) Create(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.User.Create")
defer span.End()
dbConn := u.MasterDB.Copy()
defer dbConn.Close()
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.NewShutdownError("web value missing from context")
@ -84,22 +65,16 @@ func (u *User) Create(ctx context.Context, w http.ResponseWriter, r *http.Reques
return errors.Wrap(err, "")
}
usr, err := user.Create(ctx, dbConn, &newU, v.Now)
usr, err := user.Create(ctx, u.MasterDB, &newU, v.Now)
if err != nil {
return errors.Wrapf(err, "User: %+v", &usr)
}
return web.Respond(ctx, w, usr, http.StatusCreated)
return web.RespondJson(ctx, w, usr, http.StatusCreated)
}
// Update updates the specified user in the system.
func (u *User) Update(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.User.Update")
defer span.End()
dbConn := u.MasterDB.Copy()
defer dbConn.Close()
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.NewShutdownError("web value missing from context")
@ -110,7 +85,7 @@ func (u *User) Update(ctx context.Context, w http.ResponseWriter, r *http.Reques
return errors.Wrap(err, "")
}
err := user.Update(ctx, dbConn, params["id"], &upd, v.Now)
err := user.Update(ctx, u.MasterDB, params["id"], &upd, v.Now)
if err != nil {
switch err {
case user.ErrInvalidID:
@ -124,18 +99,12 @@ func (u *User) Update(ctx context.Context, w http.ResponseWriter, r *http.Reques
}
}
return web.Respond(ctx, w, nil, http.StatusNoContent)
return web.RespondJson(ctx, w, nil, http.StatusNoContent)
}
// Delete removes the specified user from the system.
func (u *User) Delete(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.User.Delete")
defer span.End()
dbConn := u.MasterDB.Copy()
defer dbConn.Close()
err := user.Delete(ctx, dbConn, params["id"])
err := user.Delete(ctx, u.MasterDB, params["id"])
if err != nil {
switch err {
case user.ErrInvalidID:
@ -149,18 +118,12 @@ func (u *User) Delete(ctx context.Context, w http.ResponseWriter, r *http.Reques
}
}
return web.Respond(ctx, w, nil, http.StatusNoContent)
return web.RespondJson(ctx, w, nil, http.StatusNoContent)
}
// Token handles a request to authenticate a user. It expects a request using
// Basic Auth with a user's email and password. It responds with a JWT.
func (u *User) Token(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.User.Token")
defer span.End()
dbConn := u.MasterDB.Copy()
defer dbConn.Close()
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.NewShutdownError("web value missing from context")
@ -172,7 +135,7 @@ func (u *User) Token(ctx context.Context, w http.ResponseWriter, r *http.Request
return web.NewRequestError(err, http.StatusUnauthorized)
}
tkn, err := user.Authenticate(ctx, dbConn, u.TokenGenerator, v.Now, email, pass)
tkn, err := user.Authenticate(ctx, u.MasterDB, u.TokenGenerator, v.Now, email, pass)
if err != nil {
switch err {
case user.ErrAuthenticationFailure:
@ -182,5 +145,5 @@ func (u *User) Token(ctx context.Context, w http.ResponseWriter, r *http.Request
}
}
return web.Respond(ctx, w, tkn, http.StatusOK)
return web.RespondJson(ctx, w, tkn, http.StatusOK)
}

View File

@ -14,8 +14,6 @@ import (
"syscall"
"time"
"github.com/go-redis/redis"
"github.com/lib/pq"
"geeks-accelerator/oss/saas-starter-kit/example-project/cmd/web-api/handlers"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/flag"
@ -23,7 +21,9 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/go-redis/redis"
"github.com/kelseyhightower/envconfig"
"github.com/lib/pq"
"go.opencensus.io/trace"
awstrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/aws/aws-sdk-go/aws"
sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"
@ -56,9 +56,9 @@ func main() {
WriteTimeout time.Duration `default:"5s" envconfig:"HTTPS_WRITE_TIMEOUT"`
}
App struct {
Name string `default:"web-api" envconfig:"APP_NAME"`
BaseUrl string `default:"" envconfig:"APP_BASE_URL"`
TemplateDir string `default:"./templates" envconfig:"APP_TEMPLATE_DIR"`
Name string `default:"web-api" envconfig:"APP_NAME"`
BaseUrl string `default:"" envconfig:"APP_BASE_URL"`
TemplateDir string `default:"./templates" envconfig:"APP_TEMPLATE_DIR"`
DebugHost string `default:"0.0.0.0:4000" envconfig:"APP_DEBUG_HOST"`
ShutdownTimeout time.Duration `default:"5s" envconfig:"APP_SHUTDOWN_TIMEOUT"`
}
@ -69,13 +69,13 @@ func main() {
MaxmemoryPolicy string `envconfig:"REDIS_MAXMEMORY_POLICY"`
}
DB struct {
Host string `default:"127.0.0.1:5433" envconfig:"DB_HOST"`
User string `default:"postgres" envconfig:"DB_USER"`
Pass string `default:"postgres" envconfig:"DB_PASS" json:"-"` // don't print
Database string `default:"shared" envconfig:"DB_DATABASE"`
Driver string `default:"postgres" envconfig:"DB_DRIVER"`
Timezone string `default:"utc" envconfig:"DB_TIMEZONE"`
DisableTLS bool `default:"false" envconfig:"DB_DISABLE_TLS"`
Host string `default:"127.0.0.1:5433" envconfig:"DB_HOST"`
User string `default:"postgres" envconfig:"DB_USER"`
Pass string `default:"postgres" envconfig:"DB_PASS" json:"-"` // don't print
Database string `default:"shared" envconfig:"DB_DATABASE"`
Driver string `default:"postgres" envconfig:"DB_DRIVER"`
Timezone string `default:"utc" envconfig:"DB_TIMEZONE"`
DisableTLS bool `default:"false" envconfig:"DB_DISABLE_TLS"`
}
Trace struct {
Host string `default:"http://tracer:3002/v1/publish" envconfig:"TRACE_HOST"`
@ -305,7 +305,7 @@ func main() {
api := http.Server{
Addr: cfg.HTTP.Host,
Handler: handlers.API(shutdown, log, masterDB, authenticator),
Handler: handlers.API(shutdown, log, masterDb, authenticator),
ReadTimeout: cfg.HTTP.ReadTimeout,
WriteTimeout: cfg.HTTP.WriteTimeout,
MaxHeaderBytes: 1 << 20,
@ -333,13 +333,13 @@ func main() {
log.Printf("main : %v : Start shutdown..", sig)
// Create context for Shutdown call.
ctx, cancel := context.WithTimeout(context.Background(), cfg.HTTP.ShutdownTimeout)
ctx, cancel := context.WithTimeout(context.Background(), cfg.App.ShutdownTimeout)
defer cancel()
// Asking listener to shutdown and load shed.
err := api.Shutdown(ctx)
if err != nil {
log.Printf("main : Graceful shutdown did not complete in %v : %v", cfg.HTTP.ShutdownTimeout, err)
log.Printf("main : Graceful shutdown did not complete in %v : %v", cfg.App.ShutdownTimeout, err)
err = api.Close()
}