autostrada-gen

module
v0.0.0-...-7cfde4e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2022 License: MIT

README

<!DOCTYPE html>
<html>
<head>
<title>README</title>

<style>
        .copy {
            max-width: 700px; font-family: sans-serif; margin: 0 auto; line-height: 1.5;
        }
        pre {
            background-color: #eee;
            padding: 1em;
            padding-top: 0;
            overflow: auto;
        }
        table {
            border-collapse: collapse;
            width: 100%;
        }
        table+table {
            margin-top: 2em;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 0.5em;
            vertical-align: top;
        }
        td:first-child {
            width: 170px;
        }
        td code {
            white-space: nowrap;
        }
        samp {
            color: rgb(110, 110, 110);
        }
</style>
</head>
<body>
<div class="copy">
<h1>README</h1>
<p>This codebase has been generated by <a href="https://autostrada.dev/">Autostrada</a>.</p>
<h2>Getting started</h2>
<p>Make sure that you're in the root of the project directory and run the <code>cmd/web</code> application using <code>go run</code>:</p>
<pre><code>
$ go run ./cmd/web
</code></pre>
<p>Then visit <a href="https://localhost:4444">https://localhost:4444</a> in your browser. The first time you do this you will probably get a security warning because the application is using a self-signed certificate. Please go ahead and accept this.</p>
<h2>Project structure</h2>
<p>Everything in the codebase is designed to be editable. Feel free to change and adapt it to meet your needs.</p>
<table>
<tbody>
<tr>
<td><strong><code>assets</code></strong></td>
<td>Contains the non-code assets for the application.</td>
</tr>
<tr>
<td><code>↳ assets/emails/</code></td>
<td>Contains email templates.</td>
</tr>
<tr>
<td><code>↳ assets/migrations/</code></td>
<td>Contains SQL migrations.</td>
</tr>
<tr>
<td><code>↳ assets/static/</code></td>
<td>Contains static UI files (images, CSS etc).</td>
</tr>
<tr>
<td><code>↳ assets/templates/</code></td>
<td>Contains HTML templates.</td>
</tr>
<tr>
<td><code>↳ assets/efs.go</code></td>
<td>Declares an embedded filesystem containing all the assets.</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><strong><code>cmd/web</code></strong></td>
<td>Your application-specific code (handlers, routing, middleware, helpers) for dealing with HTTP requests and responses.</td>
</tr>
<tr>
<td><code>↳ cmd/web/context.go</code></td>
<td>Contains helpers for working with request context.</td>
</tr>
<tr>
<td><code>↳ cmd/web/errors.go</code></td>
<td>Contains helpers for managing and responding to error conditions.</td>
</tr>
<tr>
<td><code>↳ cmd/web/handlers.go</code></td>
<td>Contains your application HTTP handlers.</td>
</tr>
<tr>
<td><code>↳ cmd/web/main.go</code></td>
<td>The entry point for the application. Responsible for parsing configuration settings initializing dependencies and running the server. Start here when you're looking through the code.</td>
</tr>
<tr>
<td><code>↳ cmd/web/middleware.go</code></td>
<td>Contains your application middleware.</td>
</tr>
<tr>
<td><code>↳ cmd/web/routes.go</code></td>
<td>Contains your application route mappings.</td>
</tr>
<tr>
<td><code>↳ cmd/web/templates.go</code></td>
<td>Contains helpers for working with HTML templates.</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><strong><code>internal</code></strong></td>
<td>Contains various helper packages used by the application.</td>
</tr>
<tr>
<td><code>↳ internal/cookies</code></td>
<td>Contains helper functions for reading/writing signed and encrypted cookies.</td>
</tr>
<tr>
<td><code>↳ internal/database/</code></td>
<td>Contains your database-related code (setup, connection and queries).</td>
</tr>
<tr>
<td><code>↳ internal/funcs/</code></td>
<td>Contains custom template functions.</td>
</tr>
<tr>
<td><code>↳ internal/password/</code></td>
<td>Contains helper functions for hashing and verifying passwords.</td>
</tr>
<tr>
<td><code>↳ internal/leveledlog/</code></td>
<td>Contains a leveled logger implementation.</td>
</tr>
<tr>
<td><code>↳ internal/request/</code></td>
<td>Contains helper functions for decoding HTML forms and URL query strings.</td>
</tr>
<tr>
<td><code>↳ internal/response/</code></td>
<td>Contains helper functions for rendering HTML templates.</td>
</tr>
<tr>
<td><code>↳ internal/server/</code></td>
<td>Contains a helper function for starting and gracefully shutting down the server.</td>
</tr>
<tr>
<td><code>↳ internal/smtp/</code></td>
<td>Contains a SMTP sender implementation.</td>
</tr>
<tr>
<td><code>↳ internal/token/</code></td>
<td>Contains functions for generating and hashing cryptographically secure random tokens.</td>
</tr>
<tr>
<td><code>↳ internal/validator/</code></td>
<td>Contains validation helpers.</td>
</tr>
<tr>
<td><code>↳ internal/version/</code></td>
<td>Contains the application version number definition.</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><strong><code>tls</code></strong></td>
<td>Contains TLS certificates.</td>
</tr>
</tbody>
</table>
<h2>Configuration settings</h2>
<p>Configuration settings are managed via command-line flags in <code>main.go</code>.</p>
<p>You can try this out by using the <code>-addr</code> flag to configure the network address that the server is listening:</p>
<pre><code>
$ go run . --addr=:9999
</code></pre>
<p>Feel free to adapt the <code>main()</code> function to parse additional command-line flags and store their values in the <code>config</code> struct. For example, to add a configuration setting to enable a 'debug mode' in your application you could do this:</p>
<pre><code>
type config struct {
    addr string
    debug bool
}

...

func main() {
    var cfg config

    flag.StringVar(&amp;cfg.addr, "addr", ":4444", "server address")
    flag.BoolVar(&amp;cfg.debug, "debug", false, "enable debug mode")

    flag.Parse()

    ...
}
</code></pre>
<p>If you don't want to use command-line flags for configuration that's fine. Feel free to adapt the code so that the <code>config</code> struct is populated from environment variables or a settings file instead.</p>
<h2>Creating new handlers</h2>
<p>Handlers are defined as <code>http.HandlerFunc</code> methods on the <code>application</code> struct. They take the pattern:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    // Your handler logic...
}
</code></pre>
<p>Handlers are defined in the <code>cmd/web/handlers.go</code> file. For small applications, it's fine for all handlers to live in this file. For larger applications (10+ handlers) you may wish to break them out into separate files.</p>
<h2>Handler dependencies</h2>
<p>Any dependencies that your handlers have should be initialized in the <code>main()</code> function <code>cmd/web/main.go</code> and added to the <code>application</code> struct. All of your handlers, helpers and middleware that are defined as methods on <code>application</code> will then have access to them.</p>
<p>You can see an example of this in the <code>cmd/web/main.go</code> file where we initialize a new <code>logger</code> instance and add it to the <code>application</code> struct.</p>
<h2>Creating new routes</h2>
<p><a href="https://github.com/alexedwards/flow/">Flow</a> is used for routing, but it's fine to swap to a different router if you want.</p>
<p>Routes are defined in the <code>routes()</code> method in the <code>cmd/web/routes.go</code> file. For example:</p>
<pre><code>
func (app *application) routes() http.Handler {
    mux := flow.New()
    
    mux.HandleFunc("/your/path", app.yourHandler, "GET")
    
    return mux
}
</code></pre>
<p>For more information on using flow and example usage, please see the <a href="https://github.com/alexedwards/flow/">official documentation</a>.</p>
<h2>Adding middleware</h2>
<p>Middleware is defined as methods on the <code>application</code> struct in the <code>cmd/web/middleware.go</code> file. Feel free to add your own. They take the pattern:</p>
<pre><code>
func (app *application) yourMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Your middleware logic...
        next.ServeHTTP(w, r)
    })
}
</code></pre>
<p>You can then register this middleware with the router using the <code>Use()</code> method:</p>
<pre><code>
func (app *application) routes() http.Handler {
    mux := flow.New()
    mux.Use(app.yourMiddleware)
    
    mux.HandleFunc("/your/path", app.yourHandler, "GET")
    
    return mux
}
</code></pre>
<p>It's possible to use middleware on specific routes only by creating route 'groups':</p>
<pre><code>
func (app *application) routes() http.Handler {
    mux := flow.New()
    mux.Use(app.yourMiddleware)
    
    mux.HandleFunc("/your/path", app.yourHandler, "GET")

    mux.Group(func(mux *flow.Mux) {
        mux.Use(app.yourOtherMiddleware)
    
        mux.HandleFunc("/your/other/path", app.yourOtherHandler, "GET")
    })
    
    return mux
}
</code></pre>
<p>Note: Route 'groups' can also be nested.</p>
<h2>Rendering HTML templates</h2>
<p>HTML templates are stored in the <code>assets/templates</code> directory and use the standard library <code>html/template</code> package. The structure looks like this:</p>
<table>
<tbody>
<tr>
<td><code>assets/templates/base.tmpl</code></td>
<td>The 'base' template containing the shared HTML markup for all your web pages.</td>
</tr>
<tr>
<td><code>assets/templates/pages/</code></td>
<td>Directory containing files with the page-specific content for your web pages. See <code>assets/templates/pages/home.tmpl</code> for an example.</td>
</tr>
<tr>
<td><code>assets/templates/partials/</code></td>
<td>Directory containing files with 'partials' to embed in your web pages or base template. See <code>assets/templates/partials/footer.tmpl</code> for an example.</td>
</tr>
</tbody>
</table>
<p>The HTML for web pages can be sent using the <code>response.Page()</code> function. For convenience, an <code>app.newTemplateData()</code> method is provided which returns a <code>map[string]any</code> map. You can add data to this map and pass it on to your templates.</p>
<p>For example, to render the HTML in the <code>assets/templates/pages/example.tmpl</code> file:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    data := app.newTemplateData()
    data["hello"] = "world"

    err := response.Page(w, http.StatusOK, data, "pages/example.tmpl")
    if err != nil {
        app.serverError(w, r, err)
    }
}
</code></pre>
<p>Specific HTTP headers can optionally be sent with the response too:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    data := app.newTemplateData()
    data["hello"] = "world"

    headers := make(http.Header)
    headers.Set("X-Server", "Go")

    err := response.PageWithHeaders(w, http.StatusOK, data, headers, "pages/example.tmpl")
    if err != nil {
        app.serverError(w, r, err)
    }
}
</code></pre>
<p>Note: All the files in the <code>assets/templates</code> directory are embedded into your application binary and can be accessed via the <code>EmbeddedFiles</code> variable in <code>assets/efs.go</code>.</p>
<h2>Adding default template data</h2>
<p>If you have data that you want to display or use on multiple web pages, you can adapt the <code>newTemplateData()</code> helper in the <code>templates.go</code> file to include this by default. For example, if you wanted to include the current year value you could adapt it like this:</p>
<pre><code>
func (app *application) newTemplateData() map[string]any {
    data := map[string]any{
        "CurrentYear": time.Now().Year(),
    }

    return data
}    
</code></pre>
<h2>Custom template functions</h2>
<p>Custom template functions are defined in <code>internal/funcs/funcs.go</code> and are automatically made available to your HTML templates when you use <code>response.Page()</code> and email templates when you use <code>app.mailer.Send()</code> .</p>
<p>The following custom template functions are already included by default:</p>
<table>
<tbody>
<tr>
<td><code>now</code></td>
<td>Returns the current time.</td>
</tr>
<tr>
<td><code>timeSince arg1</code></td>
<td>Returns the time elapsed since arg1.</td>
</tr>
<tr>
<td><code>timeUntil arg2</code></td>
<td>Returns the time until arg1.</td>
</tr>
<tr>
<td><code>formatTime arg1 arg2</code></td>
<td>Returns the time arg2 as formatted using the pattern arg1.</td>
</tr>
<tr>
<td><code>approxDuration arg1</code></td>
<td>Returns the approximate duration of arg1 in a 'human-friendly' format ("3 seconds", "2 months", "5 years") etc.</td>
</tr>
<tr>
<td><code>uppercase arg1</code></td>
<td>Returns arg1 converted to uppercase.</td>
</tr>
<tr>
<td><code>lowercase arg1</code></td>
<td>Returns arg1 converted to lowercase.</td>
</tr>
<tr>
<td><code>pluralize arg1 arg2 arg3</code></td>
<td>If arg1 equals 1 then return arg2, otherwise return arg3.</td>
</tr>
<tr>
<td><code>slugify arg1</code></td>
<td>Returns the lowercase of arg1 with all non-ASCII characters and punctuation removed (expect underscores and hyphens). Whitespaces are also replaced with a hyphen.</td>
</tr>
<tr>
<td><code>safeHTML arg1</code></td>
<td>Output the verbatim value of arg1 without escaping the content. This should only be used when arg1 is from a trusted source.</td>
</tr>
<tr>
<td><code>join arg1 arg2</code></td>
<td>Returns the values in arg1 joined using the separator arg2.</td>
</tr>
<tr>
<td><code>containsString arg1 arg2</code></td>
<td>Returns true if arg1 contains the string value arg2.</td>
</tr>
<tr>
<td><code>incr arg1</code></td>
<td>Increments arg1 by 1.</td>
</tr>
<tr>
<td><code>decr arg1</code></td>
<td>Decrements arg1 by 1.</td>
</tr>
<tr>
<td><code>formatInt arg1</code></td>
<td>Returns arg1 formatted with commas as the thousands separator.</td>
</tr>
<tr>
<td><code>formatFloat arg1 arg2</code></td>
<td>Returns arg1 rounded to arg2 decimal places and formatted with commas as the thousands separator.</td>
</tr>
<tr>
<td><code>yesno arg1</code></td>
<td>Returns "Yes" if arg1 is true, or "No" if arg1 is false.</td>
</tr>
<tr>
<td><code>urlSetParam arg1 arg2 arg3</code></td>
<td>Returns the URL arg1 with the key arg2 and value arg3 added to the query string parameters.</td>
</tr>
<tr>
<td><code>urlDelParam arg1 arg2</code></td>
<td>Returns the URL arg1 with the key arg2 (and corresponding value) removed from the query string parameters.</td>
</tr>
</tbody>
</table>
<p>To add another custom template function, define the function in <code>internal/funcs/funcs.go</code> and add it to the <code>TemplateFuncs</code> map. For example:</p>
<pre><code>
var TemplateFuncs = template.FuncMap{
    ...
    "yourFunction": yourFunction, 
}

func yourFunction(s string) (string, error) {
    // Do something...
}
</code></pre>
<h2>Static files</h2>
<p>By default, the files in the <code>assets/static</code> directory are served using Go's <code>http.Fileserver</code> whenever the application receives a <code>GET</code> request with a path beginning <code>/static/</code>. So, for example, if the application receives a <code>GET /static/css/main.css</code> request it will respond with the contents of the <code>assets/static/css/main.css</code> file.</p>
<p>If you want to change or remove this behavior you can by editing the <code>routes.go</code> file.</p>
<p>Note: The files in <code>assets/static</code> directory are embedded into your application binary and can be accessed via the <code>EmbeddedFiles</code> variable in <code>assets/efs.go</code>.</p>
<h2>Working with forms</h2>
<p>The codebase includes a <code>request.DecodePostForm()</code> function for automatically decoding HTML form data into a struct, and <code>request.DecodeQueryString()</code> for decoding URL query strings into a struct. Behind the scenes this decoding is managed using the <a href="https://github.com/go-playground/form">go-playground/form</a> package.</p>
<p>As an example, let's say you have a page with the following HTML form for creating a 'person' record and routing rule:</p>
<pre><code>
&lt;form action="/person/create" method="POST"&gt;
    &lt;div&gt;
        &lt;label&gt;Your name:&lt;/label&gt;
        &lt;input type="text" name="Name" value="{{.Form.Name}}"&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;label&gt;Your age:&lt;/label&gt;
        &lt;input type="number" name="Age" value="{{.Form.Age}}"&gt;
    &lt;/div&gt;
    &lt;button&gt;Submit&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<pre><code>
func (app *application) routes() http.Handler {
    mux := flow.New()
    
    mux.HandleFunc("/person/create", app.createPerson, "GET", "POST")
    
    return mux
}
</code></pre>
<p>Then you can display and parse this form with a <code>createPerson</code> handler like this:</p>
<pre><code>
package main

import (
    "net/http"

    "github.com/gonzaloserrano/autostrada-gen/internal/request"
    "github.com/gonzaloserrano/autostrada-gen/internal/response"
)

func (app *application) createPerson(w http.ResponseWriter, r *http.Request) {
    type createPersonForm struct {
        Name string `form:"Name"`
        Age  int    `form:"Age"`
    }

    switch r.Method {
    case http.MethodGet:
        data := app.newTemplateData()

        // Add any default values to the form.
        data["Form"] = createPersonForm{
            Age: 21,
        }

        err := response.Page(w, http.StatusOK, data, "/path/to/page.tmpl")
        if err != nil {
            app.serverError(w, r, err)
        }

    case http.MethodPost:
        var form createPersonForm

        err := request.DecodePostForm(r, &amp;form)
        if err != nil {
            app.badRequest(w, r, err)
            return
        }
    
        // Do something with the data in the form variable...
    }
}    
</code></pre>
<h2>Validating forms</h2>
<p>The <code>internal/validator</code> package includes a simple (but powerful) <code>validator.Validator</code> type that you can use to carry out validation checks.</p>
<p>Extending the example above:</p>
<pre><code>
package main

import (
    "net/http"

    "github.com/gonzaloserrano/autostrada-gen/internal/request"
    "github.com/gonzaloserrano/autostrada-gen/internal/response"
    "github.com/gonzaloserrano/autostrada-gen/internal/validator"
)

func (app *application) createPerson(w http.ResponseWriter, r *http.Request) {
    type createPersonForm struct {
        Name      string              `form:"Name"`
        Age       int                 `form:"Age"`
        Validator validator.Validator `form:"-"`
    }

    switch r.Method {
    case http.MethodGet:
        data := app.newTemplateData()

        // Add any default values to the form.
        data["Form"] = createPersonForm{
            Age: 21,
        }

        err := response.Page(w, http.StatusOK, data, "/path/to/page.tmpl")
        if err != nil {
            app.serverError(w, r, err)
        }

    case http.MethodPost:
        var form createPersonForm

        err := request.DecodePostForm(r, &amp;form)
        if err != nil {
            app.badRequest(w, r, err)
            return
        }

        form.Validator.CheckField(form.Name != "", "Name", "Name is required")
        form.Validator.CheckField(form.Age != 0, "Age", "Age is required")
        form.Validator.CheckField(form.Age &gt;= 21, "Age", "Age must be 21 or over")

        if form.Validator.HasErrors() {
            data := app.newTemplateData()
            data["Form"] = form

            err := response.Page(w, http.StatusUnprocessableEntity, data, "/path/to/page.tmpl")
            if err != nil {
                app.serverError(w, r, err)
            }
            return
        }

        // Do something with the form information, like adding it to a database...
    }
}    
</code></pre>
<p>And you can display the error messages in your HTML form like this:</p>
<pre><code>
&lt;form action="/person/create" method="POST"&gt;
    {{if .Form.Validator.HasErrors}}
        &lt;p&gt;Something was wrong. Please correct the errors below and try again.&lt;/p&gt;
    {{end}}
    &lt;div&gt;
        &lt;label&gt;Your name:&lt;/label&gt;
        {{with .Form.Validator.FieldErrors.Name}}
            &lt;span class='error'&gt;{{.}}&lt;/span&gt;
        {{end}}
        &lt;input type="text" name="Name" value="{{.Form.Name}}"&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;label&gt;Your age:&lt;/label&gt;
        {{with .Form.Validator.FieldErrors.Age}}
            &lt;span class='error'&gt;{{.}}&lt;/span&gt;
        {{end}}
        &lt;input type="number" name="Age" value="{{.Form.Age}}"&gt;
    &lt;/div&gt;
    &lt;button&gt;Submit&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<p>In the example above we use the <code>CheckField()</code> method to carry out validation checks for specific fields. You can also use the <code>Check()</code> method to carry out a validation check that is <em>not related to a specific field</em>. For example:</p>
<pre><code>
input.Validator.Check(input.Password == input.ConfirmPassword, "Passwords do not match")
</code></pre>
<p>The <code>validator.AddError()</code> and <code>validator.AddFieldError()</code> methods also let you add validation errors directly:</p>
<pre><code>
input.Validator.AddFieldError("Email", "This email address is already taken")
input.Validator.AddError("Passwords do not match")
</code></pre>
<p>The <code>internal/validator/helpers.go</code> file also contains some helper functions to simplify validations that are not simple comparison operations.</p>
<table>
<tbody>
<tr>
<td><code>NotBlank(value string)</code></td>
<td>Check that the value contains at least one non-whitespace character.</td>
</tr>
<tr>
<td><code>MinRunes(value string, n int)</code></td>
<td>Check that the value contains at least n runes.</td>
</tr>
<tr>
<td><code>MaxRunes(value string, n int)</code></td>
<td>Check that the value contains no more than n runes.</td>
</tr>
<tr>
<td><code>Between(value, min, max T)</code></td>
<td>Check that the value is between the min and max values inclusive.</td>
</tr>
<tr>
<td><code>Matches(value string, rx *regexp.Regexp)</code></td>
<td>Check that the value matches a specific regular expression.</td>
</tr>
<tr>
<td><code>In(value T, safelist ...T)</code></td>
<td>Check that a value is in a 'safelist' of specific values.</td>
</tr>
<tr>
<td><code>AllIn(values []T, safelist ...T)</code></td>
<td>Check that all values in a slice are in a 'safelist' of specific values.</td>
</tr>
<tr>
<td><code>NotIn(value T, blocklist ...T)</code></td>
<td>Check that the value is not in a 'blocklist' of specific values.</td>
</tr>
<tr>
<td><code>NoDuplicates(values []T)</code></td>
<td>Check that a slice does not contain any duplicate (repeated) values.</td>
</tr>
<tr>
<td><code>IsEmail(value string)</code></td>
<td>Check that the value has the formatting of a valid email address.</td>
</tr>
<tr>
<td><code>IsURL(value string)</code></td>
<td>Check that the value has the formatting of a valid URL.</td>
</tr>
</tbody>
</table>
<p>For example, to use the <code>Between</code> check your code would look similar to this:</p>
<pre><code>
input.Validator.CheckField(validator.Between(input.Age, 18, 30), "Age", "Age must between 18 and 30")
</code></pre>
<p>Feel free to add your own helper functions to the <code>internal/validator/helpers.go</code> file as necessary for your application.</p>
<h2>Working with the database</h2>
<p>This codebase is set up to use SQLite3 with the <a href="https://github.com/mattn/go-sqlite3">mattn/go-sqlite3</a> driver. The data is stored in a <code>db.sqlite</code> file in the project root, but you can change this by passing a different DSN (datasource name) in the <code>-db-dsn</code> command-line flag when starting the application, or by adapting the default value in <code>main()</code>.</p>
<p>The codebase is also configured to use <a href="https://github.com/jmoiron/sqlx">jmoiron/sqlx</a>, so you have access to the whole range of sqlx extensions as well as the standard library <code>Exec()</code>, <code>Query()</code> and <code>QueryRow()</code> methods .</p>
<p>The database is available to your handlers, middleware and helpers via the <code>application</code> struct. If you want, you can access the database and carry out queries directly. For example:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    ...

    _, err := app.db.Exec("INSERT INTO people (name, age) VALUES ($1, $2)", "Alice", 28)
    if err != nil {
        app.serverError(w, r, err)
        return
    }
    
    ...
}
</code></pre>
<p>Generally though, it's recommended to isolate your database logic in the <code>internal/database</code> package and extend the <code>DB</code> type to include your own methods. For example, you could create a <code>internal/database/people.go</code> file containing code like:</p>
<pre><code>
type Person struct {
    ID    int    `db:"id"`
    Name  string `db:"name"`
    Age   int    `db:"age"`
}

func (db *DB) NewPerson(name string, age int) error {
    _, err := db.Exec("INSERT INTO people (name, age) VALUES ($1, $2)", name, age)
    return err
}

func (db *DB) GetPerson(id int) (Person, error) {
    var person Person
    err := db.Get(&amp;person, "SELECT * FROM people WHERE id = $1", id)
    return person, err
}
</code></pre>
<p>And then call this from your handlers:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    ...

    _, err := app.db.NewPerson("Alice", 28)
    if err != nil {
        app.serverError(w, r, err)
        return
    }
    
    ...
}
</code></pre>
<h2>Managing SQL migrations</h2>
<p>The <code>Makefile</code> in the project root contains commands to easily create and work with database migrations:</p>
<table>
<tbody>
<tr>
<td><code>$ make migrations/new name=add_example_table</code></td>
<td>Create a new database migration in the <code>assets/migrations</code> folder.</td>
</tr>
<tr>
<td><code>$ make migrations/up</code></td>
<td>Apply all up migrations.</td>
</tr>
<tr>
<td><code>$ make migrations/down</code></td>
<td>Apply all down migrations.</td>
</tr>
<tr>
<td><code>$ make migrations/goto version=N</code></td>
<td>Migrate up or down to a specific migration (where N is the migration version number).</td>
</tr>
<tr>
<td><code>$ make migrations/force version=N</code></td>
<td>Force the database to be specific version without running any migrations.</td>
</tr>
<tr>
<td><code>$ make migrations/version</code></td>
<td>Display the currently in-use migration version.</td>
</tr>
</tbody>
</table>
<p>Hint: You can run <code>$ make help</code> at any time for a reminder of these commands.</p>
<p>These <code>Makefile</code> tasks are simply wrappers around calls to the <code>github.com/golang-migrate/migrate/v4/cmd/migrate</code> tool. For more information, please see the <a href="https://github.com/golang-migrate/migrate/tree/master/cmd/migrate">official documentation</a>.</p>
<p>By default all 'up' migrations are automatically run on application startup using embeded files from the <code>assets/migrations</code> directory. You can disable this by using the command-line flag <code>-db-automigrate=false</code> when running the application.</p>
<p>Important: If you change your database location from the default <code>db.sqlite</code> file then you will need to also update the <code>Makefile</code> tasks to reference the new location.</p>
<h2>Logging</h2>
<p>The <code>internal/leveledlog</code> package provides a leveled-logger implementation. It outputs color-coded log lines in the following format:</p>
<pre><code>
level="INFO" time="2022-08-15T08:51:09+02:00" message="starting server on localhost:4444 (version 0.0.1)"
</code></pre>
<p>By default, a logger is initialized in the <code>main()</code> function which writes all log messages to <code>os.Stdout</code>. You can call the logger's <code>Info()</code>, <code>Warn()</code>, <code>Error()</code> and <code>Fatal()</code> methods to log messages at different levels with <code>fmt.Printf</code> style formatting. For example:</p>
<pre><code>
logger.Info("starting server on port %d", 1234)
</code></pre>
<p>Note: Stack traces are automatically appended to <code>Error()</code> and <code>Fatal()</code> messages, and calling <code>Fatal()</code> will cause your application to terminate.</p>
<p>If you want to disable the color-coding, then pass <code>false</code> as the final parameter when initializing the logger in <code>main()</code>.</p>
<pre><code>
logger := leveledlog.NewLogger(os.Stdout, leveledlog.LevelAll, false)
</code></pre>
<p>You can also write JSON-formated log entries instead by using the <code>NewJSONLogger()</code> function to initialize the logger:</p>
<pre><code>
logger := leveledlog.NewJSONLogger(os.Stdout, leveledlog.LevelAll)
</code></pre>
<p>Note: JSON-formatted log entries are not color-coded.</p>
<p>Feel free to adapt the <code>internal/leveledlog</code> package to change this behavior or include additional fields if you want.</p>
<h2>Cookies</h2>
<p>The <code>internal/cookies</code> package provides helper functions for reading and writing cookies.</p>
<p>The <code>Write()</code> function base64-encodes the cookie value and checks the cookie length is no more than 4096 bytes before writing the cookie. You can use it like this:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    // Initialize a Go cookie as normal.
    cookie := http.Cookie{
        Name:     "exampleCookie",
        Value:    "Hello Zoë!",
        Path:     "/",
        MaxAge:   3600,
        HttpOnly: true,
        Secure:   true,
        SameSite: http.SameSiteLaxMode,
    }

    // Write the cookie.
    err := cookies.Write(w, cookie)
    if err != nil {
        app.serverError(w, r, err)
        return
    }

    ...
}
</code></pre>
<p>The <code>Read()</code> function reads a named cookie and base64-decodes the value before returning it.</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    // Read the cookie value and handle any errors as necessary for your application.
    value, err := cookies.Read(r, "exampleCookie")
    if err != nil {
        switch {
        case errors.Is(err, http.ErrNoCookie):
            app.badRequest(w, r, err)
        case errors.Is(err, cookies.ErrInvalidValue):
            app.badRequest(w, r, err)
        default:
            app.serverError(w, r, err)
        }
        return
    }

    ...
}
</code></pre>
<p>The <code>internal/cookies</code> package also provides <code>WriteSigned()</code> and <code>ReadSigned()</code> functions for writing/reading signed cookies, and <code>WriteEncrypted()</code> and <code>ReadEncrypted()</code> functions encrypted cookies. Signed cookies are authenticated using HMAC-256, meaning that you can trust that the contents of the cookie has not been tampered with. Encrypted cookies are encrpyted using AES-GCM, which both authenticates and encrypts the cookie data, meaning that you can trust that the contents of the cookie has not been tampered with <em>and</em> the contents of the cookie cannot be read by the client.</p>
<p>When using these helper functions, you must set your own (secret) key for signing and encryption. This key should be a random 32-character string generated using a CSRNG which you pass to the application using the <code>-cookie-key</code> command-line flag. For example:</p>
<pre><code>
$ go run ./cmd/web --cookie-secret-key=heoCDWSgJ430OvzyoLNE9mVV9UJFpOWx
</code></pre>
<p>To write a new signed or encrypted cookie:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    // Initialize a Go cookie as normal.
    cookie := http.Cookie{
        Name:     "exampleCookie",
        Value:    "Hello Zoë!",
        Path:     "/",
        MaxAge:   3600,
        HttpOnly: true,
        Secure:   true,
        SameSite: http.SameSiteLaxMode,
    }

    // Write a signed cookie using WriteSigned() and passing in the secret key
    // as the final argument. Use WriteEncrypted() if you want an encrpyted
    // cookie instead.
    err := cookies.WriteSigned(w, cookie, app.config.cookie.secretKey)
    if err != nil {
        app.serverError(w, r, err)
        return
    }

    ...
}
</code></pre>
<p>To read a signed or encrypted cookie:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    // Read the cookie value using ReadSigned() and passing in the secret key
    // as the final argument. Use ReadEncrypted() if you want to read an 
    // encrpyted cookie instead.
    value, err := cookies.ReadSigned(r, "exampleCookie", app.config.cookie.secretKey)
    if err != nil {
        switch {
        case errors.Is(err, http.ErrNoCookie):
            app.badRequest(w, r, err)
        case errors.Is(err, cookies.ErrInvalidValue):
            app.badRequest(w, r, err)
        default:
            app.serverError(w, r, err)
        }
        return
    }

    ...
}
</code></pre>
<h2>Using Basic Authentication</h2>
<p>The <code>cmd/web/middleware.go</code> file contains a <code>basicAuth</code> middleware that you can use to protect your application — or specific application routes — with HTTP basic authentication.</p>
<p>You can try this out by visiting the <a href="https://localhost:4444//basic-auth-protected">https://localhost:4444//basic-auth-protected</a> endpoint in any web browser and entering the default user name and password:</p>
<pre><code>
User name: admin
Password:  pa55word
</code></pre>
<p>You can change the user name and password by passing <code>-auth-username</code> and <code>-auth-hashed-password</code> command-line flags when starting the application. For example:</p>
<pre><code>
$ go run ./cmd/web --auth-username='alice' --auth-hashed-password='$2a$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
</code></pre>
<p>Note: You will probably need to wrap the username and password in <code>'</code> quotes to prevent your shell interpreting dollar and slash symbols as special characters.</p>
<p>The value for <code>-auth-hashed-password</code> should be a bcrypt hash of the password, not the plaintext password itself. An easy way to generate the bcrypt hash for a password is to use the <code>gophers.dev/cmds/bcrypt-tool</code> package like so:</p>
<pre><code>
$ go run gophers.dev/cmds/bcrypt-tool@latest hash 'your_pa55word'
</code></pre>
<p>If you want to change the default values for username and password you can do so by editing the default command-line flag values in the <code>cmd/web/main.go</code> file.</p>
<h2 id="using-sessions">Using sessions</h2>
<p>The codebase is set up so that cookie-based sessions (using the <a href="https://github.com/gorilla/sessions">gorilla/sessions</a> package) work out-of-the-box.</p>
<p>You can use them in your handlers like this:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    ...

    session, err := app.sessionStore.Get(r, "sessions")
    if err != nil {
        app.serverError(w, r, err)
        return
    }

    session.Values["foo"] = "bar"

    err = session.Save(r, w)
    if err != nil {
        app.serverError(w, r, err)
        return
    }
    
    ...
}
</code></pre>
<p>By default sessions are set to expire after 1 week. You can configure this along with other session cookie settings in the <code>cmd/web/main.go</code> file by changing the <code>sessions.Options</code> struct values:</p>
<pre><code>
sessionStore.Options = &amp;sessions.Options{
    HttpOnly: true,
    MaxAge:   86400 * 7, // 1 week in seconds
    Path:     "/",
    SameSite: http.SameSiteLaxMode,
}
</code></pre>
<p>When running the application in production you should use your own secret key for authenticating sessions. This key should be a random 32-character string generated using a CSRNG which you pass to the application using the <code>-session-key</code> command-line flag.</p>
<pre><code>
$ go run ./cmd/web --session-secret-key=npsqT5At8USavGtyRpr4tc8j9hWK2Yol
</code></pre>
<p>Key rotation is supported. If you want to switch to a new key run the application using the <code>-session-key</code> for the new key and the <code>-session-old-key</code> flag for the old key, until all sessions using the old key have expired.</p>
<pre><code>
$ go run ./cmd/web --session-secret-key=SfvzdTUOHeHkavOzRP6p1uUVpueX11mW --session-old-secret-key=npsqT5At8USavGtyRpr4tc8j9hWK2Yol
</code></pre>
<p>For more information please see the <a href="https://github.com/gorilla/sessions">documentation for the gorilla/sessions package</a>.</p>
<h2 id="sending-emails">Sending emails</h2>
<p>The application is configured to support sending of emails via SMTP.</p>
<p>Email templates should be defined as files in the <code>assets/emails</code> folder. Each file should contain named templates for the email subject, plaintext body and — optionally — HTML body.</p>
<pre><code>
{{define "subject"}}Example subject{{end}}

{{define "plainBody"}} 
This is an example body
{{end}}
    
{{define "htmlBody"}}
&lt;!doctype html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta name="viewport" content="width=device-width" /&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;p&gt;This is an example body&lt;/p&gt;
    &lt;/body&gt;
&lt;/html&gt;
{{end}}
</code></pre>
<p>A further example can be found in the <code>assets/emails/example.tmpl</code> file. Note that your email templates automatically have access to the custom template functions defined in the <code>internal/funcs</code> package.</p>
<p>Emails can be sent from your handlers using <code>app.mailer.Send()</code>. For example, to send an email to <code>alice@github.com/gonzaloserrano/autostrada-gen</code> containing the contents of the <code>assets/emails/example.tmpl</code> file:</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    ...

    data := map[string]any{"Name": "Alice"}

    err := app.mailer.Send("alice@github.com/gonzaloserrano/autostrada-gen", data, "example.tmpl")
    if err != nil {
        app.serverError(w, r, err)
        return
    }

   ...
}
</code></pre>
<p>Note: The second parameter to <code>Send()</code> should be a map or struct containing any dynamic data that you want to render in the email template.</p>
<p>The SMTP host, port, username, password and sender details can be configured using the <code>-smtp-host</code>, <code>-smtp-port</code>, <code>-smtp-username</code>, <code>-smtp-password</code> and <code>-smtp-from</code> command-line flags when starting the application, or by adapting the default values in <code>cmd/web/main.go</code>.</p>
<p>You may wish to use <a href="https://mailtrap.io/">Mailtrap</a> or a similar tool for development purposes.</p>
<h2>User accounts</h2>
<p>The application is configured to support user accounts with fully-functional signup, login, logout and password-reset workflows.</p>
<p>A <code>User</code> struct describing the data for a user is defined in <code>internal/database/users.go</code>.</p>
<pre><code>
type User struct {
    ID             int       `db:"id"`
    Created        time.Time `db:"created"`
    Email          string    `db:"email"`
    HashedPassword string    `db:"hashed_password"`
}
</code></pre>
<p>Feel free to add additional fields to this struct (don't forget to also update the SQL queries, migrations, and handler code as necessary!).</p>
<p>By default login is done using the user's email address and password. When a login is successful the user's ID is stored in the session cookie. When this cookie is sent back with subsequent requests to the application, the <code>authenticate</code> middleware is used to look up the user's information from the database. The user's information is then stored in the current request context.</p>
<p>By default the session cookie lifetime is 1 week (meaning that a user will remain logged in for up to one week). You can change this value in <code>cmd/web/main.go</code> (see the <a href="#using-sessions">using sessions</a> section for more information).</p>
<p>You can control access to specific handlers based on whether a user is logged-in or not using the <code>requireAuthenticatedUser</code> and <code>requireAnonymousUser</code> middleware. An example of using these can be seen in the <code>cmd/web/routes.go</code> file.</p>
<p>Important: You should only call the <code>requireAuthenticatedUser</code> and <code>requireAnonymousUser</code> middleware <em>after</em> the <code>authenticate</code> middleware.</p>
<p>You can retrieve the details of the current user in your application handlers by calling the <code>contextGetAuthenticatedUser()</code> helper. This will return <code>nil</code> if the request is not being made by an authenticated (logged-in) user.</p>
<pre><code>
func (app *application) yourHandler(w http.ResponseWriter, r *http.Request) {
    ...

    authenticatedUser := contextGetAuthenticatedUser(r)
    
    ...
}
</code></pre>
<p>For authenticated (logged-in) users, their information is also automatically available to your HTML templates via <code>{{.AuthenticatedUser}}</code>. Again, this will be <code>nil</code> if the current user is anonymous (not logged in), meaning that you can check if a user is logged in with <code>{{if .AuthenticatedUser}}...{{end}}</code> in your HTML templates. An example of this can be seen in <code>assets/templates/partials/nav.tmpl</code>.</p>
<p>The password reset functionality sends an email to the user. The email template for this is located at <code>assets/emails/forgotten-password.tmpl</code>. Please make sure that you have configured a SMTP host, port, username, password and sender details (see the <a href="#sending-emails">sending emails</a> section above for more information).</p>
<p>When using user accounts, all <a href="https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP">non-safe</a> requests to the application require protection from CSRF attacks. Make sure to include a hidden input containing a CSRF token in any of your HTML forms that make a <code>POST</code> request:</p>
<pre><code>
&lt;input type='hidden' name='csrf_token' value='{{.CSRFToken}}'&gt;
</code></pre>
<h2>Admin tasks</h2>
<p>The <code>Makefile</code> in the project root contains commands to easily run common admin tasks:</p>
<table>
<tbody>
<tr>
<td><code>$ make tidy</code></td>
<td>Format all code using <code>go fmt</code> and tidy the <code>go.mod</code> file.</td>
</tr>
<tr>
<td><code>$ make audit</code></td>
<td>Run <code>go vet</code>, <code>staticheck</code>, execute all tests and verify required modules.</td>
</tr>
<tr>
<td><code>$ make build</code></td>
<td>Build a binary for the <code>cmd/web</code> application and store it in the <code>bin</code> folder.</td>
</tr>
<tr>
<td><code>$ make run</code></td>
<td>Build and then run a binary for the <code>cmd/web</code> application.</td>
</tr>
</tbody>
</table>
<h2>Changing the TLS certificates</h2>
<p>For convenience a self-signed TLS certificate (<code>cert.pem</code>) and private key (<code>key.pem</code>) are provided in the <code>tls</code> directory.</p>
<p>You can specify a different certificate and key at runtime using the <code>tls-cert-file</code> and <code>tls-key-file</code> command-line flags.</p>
<pre><code>
$ go run . --tls-cert-file=/path/to/cert.pem --tls-key-file=/path/to/key.pem
</code></pre>
<h2>Application version</h2>
<p>The application version number is generated automatically based on your latest version control system revision number. If you are using Git, this will be your latest Git commit hash. It can be retrieved by calling the <code>version.Get()</code> function from the <code>internal/version</code> package.</p>
<p>Important: The version control system revision number will only be available when the application is built using <code>go build</code>. If you run the application using <code>go run</code> then <code>version.Get()</code> will return the string <code>"unavailable"</code>.</p>
<h2>Changing the module path</h2>
<p>The module path is currently set to <code>github.com/gonzaloserrano/autostrada-gen</code>. Please find and replace all instances of <code>github.com/gonzaloserrano/autostrada-gen</code> in the codebase with your own module path.</p>
</div>
<!--------------------------------------------------------------------
Admin
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
HTTPS
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Module path
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Version
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Logging
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Database
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Config
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Web:Templates
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Web:Static
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Web:Forms
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
API:Sending
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
API:Decoding
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Funcs
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Validator
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Middleware
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Middleware
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Middleware
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Structure
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Start
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Migrations
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Basic Auth
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Sessions
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
SMTP
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
ACCOUNTS (WEB)
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
ACCOUNTS (API)
------------------------------------------------------------------ -->
<!--------------------------------------------------------------------
Cookies
------------------------------------------------------------------ -->
</body>
</html>

Directories

Path Synopsis
cmd
web
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL