1

again I'm stuck. I've been experimenting with Golang using this page as a guide for templates to create a master page. I've managed to get the Go server up with my CSS and JS directories all updated correctly but I am only able to load the index.html page and not the about.html page. Github link here

I have already tried the solutions in here and here but no luck, both the about page and index page are in the same directory and share the same header, footer and navigation bar templates.

I have also tried parsing files manually with template.Must(template.ParseFiles("header.html", ..... and also tried executing with the .html in the name templ.ExecuteTemplate(w, "about.html", &Page{Title: "About TL;DR"}) which does not return an error but instead just loads a blank screen. Any help will be greatly appreciated, thank you in advance!

File directory:

File directory structure

servermain.go

package main

    import (
        "fmt"
        "html/template"
        "log"
        "net/http"
        "os"
        "path/filepath"
        "strings"
    )

    //Page title
    type Page struct {
        Title string
    }

    //------------------------------Global Variables-------------------------------------//
    //Compile templates on start
    var templ = ParseTemplates()

    //ParseTemplates use for multi directory html parsing
    func ParseTemplates() *template.Template {
        t := template.New("Base")
        err := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
            if strings.Contains(path, ".html") {
                _, err = t.ParseFiles(path)
                fmt.Println(path)
                if err != nil {
                    logger.Println(err)
                    fmt.Println(err)
                }
            }

            return err
        })

        if err != nil {
            panic(err)
        }

        return t
    }

    //logging
    var errorlog *os.File
    var logger *log.Logger

    //---------------------------------------Page Handlers----------------------------------//
    //Handler for homepage
    func homepageHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Home")
        err := templ.ExecuteTemplate(w, "index", &Page{Title: "Welcome to TL;DR"})
        if err != nil {
            fmt.Println(err)
            logger.Println(err)
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    }

    //Handler for about page
    func aboutHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Println("About")
        err := templ.ExecuteTemplate(w, "about", &Page{Title: "About TL;DR"})
        if err != nil {
            fmt.Println(err)
            logger.Println(err)
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    }

    //Server log to file
    func init() {
        errorlog, err := os.OpenFile("serverlog.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
        if err != nil {
            fmt.Printf("Error opening file: %v", err)
            os.Exit(1)
        }
        log.SetOutput(errorlog)
        logger = log.New(errorlog, "\r\nTDLR : ", log.Lshortfile|log.LstdFlags)
    }

    func main() {
        //--------------------------------------Routers-------------------------------------//
        http.HandleFunc("/", homepageHandler)
        http.HandleFunc("/index", homepageHandler)
        http.HandleFunc("/about", aboutHandler)

        http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
        //---------------------------------------------------------------------------------//
        //start server
        fmt.Println("Starting server on port 9090")
        logger.Println("Starting server on port 9090")
        logger.Fatal(http.ListenAndServe(":9090", nil))

    }

Error page

Error page

Also I noticed no matter what page I load it will always execute the homepageHandler after executing the aboutHandler as can be seen in the console.

Console result

Edit: Solved 20181215 Improper definition of the about.html template, change to {{define "about"}} solved the problem.

Jian Zhen Ng
  • 61
  • 2
  • 6
  • Show us your `about.html`. – icza Dec 15 '18 at 13:44
  • https://github.com/jzng89/TLDR-GO/blob/master/about.html#L1 You have to decide which is it, about or index? None of your template files defines an "about" template, no matter their filenames. – mkopriva Dec 15 '18 at 13:50
  • @mkopriva OMG thank you for pointing that out! I did not notice that I did not change the {{define ""}} parameter in the template when I was converting the the files into Go template formats. Can't believe after 6 hours of troubleshooting I did not notice that. – Jian Zhen Ng Dec 15 '18 at 14:43

1 Answers1

0

I tested your code in my PC, it works OK. If you see a blank screen with about.html ( .html in the name ) it's probably your template's problem.
Make sure you have below code inside your about.html

{{.Title}}
Mostafa Solati
  • 1,235
  • 2
  • 13
  • 33