How to use CSS in html/template

Hi everyone !

I have built a small Go Server.

Project Tree :

-css
---- style.css

-gohtml
---- index.html
---- about.html

*server.go :

package main

import (

"net/http"

"html/template"

"path/filepath"

"log"

)

func main(){

// Handle client's requests to templates system

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){

// Manage template's layout path

layout_path := filepath.Join("templates","layout.gohtml")

// Manage *http.request

request_raw_path := filepath.Clean(r.URL.Path)

request_clean_path := filepath.Join("gohtml",request_raw_path)

if request_clean_path == "gohtml"{

request_clean_path = filepath.Join("gohtml","index.gohtml")

}else{

request_clean_path += ".gohtml"

}

// Parse layout and client's request files

template_page, err := template.ParseFiles(layout_path, request_clean_path)

if err != nil{

log.Println("Error : Failed to parse files")

log.Fatal(err)

}

// Execute template on http.ResponseWriter

template_page.ExecuteTemplate(w, "layout", nil)

})

// Start server

// Error handling OK

log.Fatal(http.ListenAndServe(":8080", nil))

} 

layout.gohtml :

{{define "layout"}}

<!DOCTYPE html>

<html>

    <head>

        <meta charset="utf-8">

        <!--<link href="css/style.css" type="text/css" rel="stylesheet">-->

        <title>{{template "page_title"}}</title>

    </head>

    <body>

        {{template "page_body"}}

    </body>

</html>

{{end}}

My problem is that if I remove the comment inside layout.gohtml, the css will be seen as a request on the server and consequently won’t be loaded… because the code only search inside “gohtml”

How to solve it ?

Thanks in advance

Hi ! No one ?

Hi, @Valenciano_8,

What do you mean by:

That sounds right to me, CSS is handled client-side, so the request for that CSS file will come to the server. I think you have to change your server implementation to handle that CSS request.

It is not loaded, because you have to “point” to all folders in the tree.

func main() {
   http.HandleFunc("/", index)
   http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./public/css"))))  <-----
   http.ListenAndServe....
}

Hi guys ! Thank you for your answers.

Well, here is my code updated :

package main

import (

    "net/http"

    "html/template"

    "path/filepath"

    "log"

)

func main(){

    // Handle client's requests to templates system

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){

        // Manage template's layout path

        layout_path := filepath.Join("templates","layout.gohtml")

        // Manage *http.request

        request_raw_path := filepath.Clean(r.URL.Path)

        request_clean_path := filepath.Join("gohtml",request_raw_path)

        

        log.Println("REQUEST = ", request_clean_path)

        if request_clean_path == "gohtml"{

            request_clean_path = filepath.Join("gohtml","index.gohtml")

            log.Println("REQUEST = ", request_clean_path)

        }else{

            request_clean_path += ".gohtml"

        }

        // Parse layout and client's request files

        template_page, err := template.ParseFiles(layout_path, request_clean_path)

        if err != nil{

            log.Println("Error : Failed to parse files")

            log.Fatal(err)

        }

        

        // Execute template on http.ResponseWriter

        template_page.ExecuteTemplate(w, "layout", nil)

    })

    // Handle client's requests for CSS

    http.Handle("/css/", http.FileServer(http.Dir("./css/")))

    // Start server

    // Error handling OK

    log.Fatal(http.ListenAndServe(":8080", nil))

}

As you can see, I added :

// Handle client's requests for CSS
http.Handle("/css/", http.FileServer(http.Dir("./css/")))

@Sibert : Why using http.StripPrefix in that case ?

My project tree is just :

image

When I run the server the gohtml is loaded without any issue but the css is still not found…

Indeed if I right click on the web page > view source > and then click on the css file it returns “404 page not found”

Any idea ? :frowning:

As I wrote must Golang know your tree structure in order to be able to use it. In my example I used my own tree. I find it handy to use the common “public” folder to gather css, js, img and html folders.