dongzhi7641 2018-12-13 13:26
浏览 135
已采纳

Golang创建主布局网页

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!

  • 写回答

2条回答 默认 最新

  • dragon0118 2018-12-13 14:50
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题