Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang to create a main layout webpage

Tags:

html

go

render

I'm new to Golang and am trying to start a web server using Go. I already wrote the html, css and js for the basic layout but am having trouble displaying the website after starting the server.

Using this page as a guide link. Just using my own written html, CSS and JS files as visual layout.

What happens is the header, footer, etc combines just fine but it is displayed as text in the browser, with tags and all. I'm not sure why it is not being displayed properly. I am not sure if it could be because I'm not rendering as html using templates.HTML but I cannot find much information on this. Thank you all in advance! Go code as below: Github link

 package main

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

type Page struct {
    Title string
}

//-------------------------------------------------------------------------------------//
//Compile templates on start
var templ = func() *template.Template {
    t := template.New("")
    err := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
        if strings.Contains(path, ".html") {
            fmt.Println(path)
            _, err = t.ParseFiles(path)
            if err != nil {
                fmt.Println(err)
            }
        }
        return err
    })

    if err != nil {
        panic(err)
    }
    return t
}()

//---------------------------------------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 {
        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 {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

//Handler for test Page
func testHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
        fmt.Println("Test")
        testT, _ := template.ParseFiles("static/test.html")
        testT.Execute(w, nil)
    }
}

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

    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
    //---------------------------------------------------------------------------------//

    //log to file
    f, err := os.OpenFile("serverlog.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Fatalf("Error opening file: %v", err)
    }
    defer f.Close()
    logger := log.New(f, "Logged : ", log.LstdFlags)
    log.SetOutput(f)

    //start server
    logger.Println("Starting server on port 9090")
    logger.Fatal(http.ListenAndServe(":9090", nil))

}

Edit: Updated 20181214

File Directory

Snapshot of webpage after code update

My html code is basically the same format as the website but I do have some javascript and local css files which are part of my html (only for simple transition, no jquery). Could this affect the parsing? Go version go version go1.10.1 windows/amd64

Solved: Updated 20181215

Thanks @A.R pointing out the issue with my html header having extra characters!

like image 246
Jian Zhen Ng Avatar asked Oct 27 '25 07:10

Jian Zhen Ng


1 Answers

Try this (works for me):

package main

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

func homepageHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Home")
    templ.ExecuteTemplate(w, "main", &Page{Title: "Welcome to TL;DR"})
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("About")
    templ.ExecuteTemplate(w, "about", &Page{Title: "About TL;DR"})
}
func main() {
    http.HandleFunc("/", homepageHandler)
    http.HandleFunc("/about", aboutHandler)
    fmt.Println("Server started on port 8080")
    fmt.Println(http.ListenAndServe(":8080", nil))
}

var templ = func() *template.Template {
    t := template.New("")
    err := filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
        if strings.Contains(path, ".html") {
            fmt.Println(path)
            _, err = t.ParseFiles(path)
            if err != nil {
                fmt.Println(err)
            }
        }
        return err
    })

    if err != nil {
        panic(err)
    }
    return t
}()

type Page struct {
    Title string
}

main.html file content:

{{define "main"}}
{{template "header" .}}
<div class="content">
    <h2>Main</h2>
    <div>This is the Main page</div>
</div>
{{template "footer" .}}
{{end}}

about.html file content:

{{define "about"}}
{{template "header" .}}
<div class="content">
    <h2>About</h2>
    <div>This is the About page</div>
</div>
{{template "footer" .}}
{{end}}

footer.html file content:

{{define "footer"}}
<p class="navbar-text navbar-fixed-bottom">Go Rocks!</p>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>

</html>
{{end}}

header.html file content:

{{define "header"}}
<!DOCTYPE html>
<html>

<head>
    <title>{{.Title}}</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css">
    <style type="text/css">
        body {
            padding-bottom: 70px;
        }

        .content {
            margin: 10px;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-default" role="navigation">
        <div class="navbar-header">
            <a class="navbar-brand" href="/">Go App</a>
        </div>
        <div class="collapse navbar-collapse navbar-ex1-collapse">
            <ul class="nav navbar-nav">
                <li><a href="/">Main</a></li>
                <li><a href="/about">About</a></li>
            </ul>
        </div>
    </nav>
    {{end}}

Notes:
And see this for templates.

Edit: in your static/template/header.html file in line 2 remove extra </ before <!DOCTYPE html> (inside red circle in this image): enter image description here

like image 127
wasmup Avatar answered Oct 28 '25 22:10

wasmup