Skip to content

Commit

Permalink
Add InfoLog and ErrorLog, create helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
abneed committed May 23, 2022
1 parent fafd583 commit fb3af3a
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
11 changes: 11 additions & 0 deletions cmd/web/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import (
"fmt"
"log"
"net/http"
"os"
"time"

"github.com/abneed/bookings/helpers"
"github.com/abneed/bookings/internal/config"
"github.com/abneed/bookings/internal/handlers"
"github.com/abneed/bookings/internal/models"
Expand All @@ -18,6 +20,8 @@ const portNumber = ":8080"

var app config.AppConfig
var session *scs.SessionManager
var infoLog *log.Logger
var errorLog *log.Logger

// main is the main application function
func main() {
Expand All @@ -44,6 +48,12 @@ func run() error {
// change this to true when in production
app.InProduction = false

infoLog = log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
app.InfoLog = infoLog

errorLog = log.New(os.Stdout, "ERROR\t", log.Ldate|log.Lshortfile)
app.ErrorLog = errorLog

session = scs.New()
session.Lifetime = 24 * time.Hour
session.Cookie.Persist = true
Expand All @@ -64,6 +74,7 @@ func run() error {
repo := handlers.NewRepo(&app)
handlers.NewHandlers(repo)
render.NewTemplates(&app)
helpers.NewHelpers(&app)

return nil
}
27 changes: 27 additions & 0 deletions helpers/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package helpers

import (
"fmt"
"net/http"
"runtime/debug"

"github.com/abneed/bookings/internal/config"
)

var app *config.AppConfig

// NewHelpers sets up app config for helpers
func NewHelpers(a *config.AppConfig) {
app = a
}

func ClientError(w http.ResponseWriter, status int) {
app.InfoLog.Println("Client error with status of", status)
http.Error(w, http.StatusText(status), status)
}

func ServerError(w http.ResponseWriter, err error) {
trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
app.ErrorLog.Println(trace)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
1 change: 1 addition & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type AppConfig struct {
UseCache bool
TemplateCache map[string]*template.Template
InfoLog *log.Logger
ErrorLog *log.Logger
InProduction bool
Session *scs.SessionManager
}

0 comments on commit fb3af3a

Please sign in to comment.