1

I am starting a Go project using Echo and Templ.

I have a project structure as follows:

/
/cmd
    main.go
/static
    css
        style.css
/view
    /layout
        base.templ

The problem I am experiencing is that I don't seem to be able to include a stylesheet.

My main. go is as follows:

package main

import (
    "fmt"
    "os"

    "github.com/RollingITGuy/go-rerun-dist/handler"
    "github.com/labstack/echo/v4"
)

func main() {

    app := echo.New()
    app.Static("/static", "static")
    handler := handler.IndexHandler{}

    app.GET("/", handler.HandleShowIndex)

    err := app.Start(":5150")
    if err != nil {
        apperr := fmt.Errorf("server start failed; %w", err)
        fmt.Fprintf(os.Stderr, "%+v\n", apperr)
    }

    os.Exit(0)
}

The Templ file is:

package layout

templ Base() {
    <html>
        <head>
            <link rel="stylesheet" href="static/css/style.css" />
            <title>Here</title>
        </head>
        <body>
            { children... }
        </body>
        <footer>
        </footer>
    </html>
}

When I view the page source I get:

<link rel="stylesheet" href="static/css/style.css">

When I click the link to the stylesheet I receive:

{"message":"Not Found"}

What am I missing? What can I fix?

3
  • How are you starting the application? My guess would be that the working directory is /cmd whereas your paths assume it's the root folder (you can check this with os.Getwd()). Commented Mar 3, 2024 at 1:39
  • Brits, I want to make sure I'm understanding correctly. In the main.go file based on what you're saying I would need to adjust the app.Static("/static", "static") path? or the <link rel="stylesheet" href="static/css/style.css" /> relative to where the program is being run? Commented Mar 4, 2024 at 16:30
  • What I'm saying is that your program makes an assumption about the current working directory. If you start a terminal and cd cmd and then run your app (./cmd) it will not work because it's trying to retrieve static/css/style.css and, as this is relative to the working directory, the full path would be cmd/static/css/style.css (which does not exist). There are a number of ways to fix this (run from the project root i.e. cmd/cmd, change the working directory in the app, embed the templates in the executable etc). Commented Mar 4, 2024 at 18:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.