dongwu9063 2015-12-26 00:51
浏览 12

如何维护Golang WebApp的html文件夹结构和其他资源?

In my web application, I am maintaining the following folder structure for the web resources,

/Users/Dinesh/go/src/github.com/dineshappavoo/test-proj/
                                                      main.go
                                                      README.md
                                                      app/
                                                          about.html
                                                          home.html
                                                          server.go
                                                          resources/
                                                                   css/
                                                                   js/
                                                                   fonts/
                                                      mypack/
                                                            abc/

In server.go under app folder I am starting the web server and rendering the html etc. In main.go [under top level folder] I am trying to call the server.go function. I am doing this because I can maintain the go dependencies and easily build the project.

Here is my main.go content,

package main

import (
    "github.com/dineshappavoo/test-proj/app"
)

func main() {
    app.Main()
}

and server.go code snippet is here,

package app

import (
    "html/template"
    "io/ioutil"
    "log"
    "net"
    "net/http"
    "regexp"
    "strconv"
    ....
    ....
)


//Home page handler
func homeHandler(
    w http.ResponseWriter,
    r *http.Request,
) {
    renderTemplate(w, "home", nil)
}

//About page handler
func aboutHandler(
    w http.ResponseWriter,
    r *http.Request,
) {

    renderTemplate(w, "about", nil)
}

var templates = template.Must(template.ParseFiles("about.html", "home.html"))

func renderTemplate(
    w http.ResponseWriter,
    tmpl string,
    p interface{},
) {
    //If you use variables other than the struct u r passing as p, then "multiple response.WriteHeader calls" error may occur. Make sure you pass
    //all variables in the struct even they are in the header.html embedded
    if err := templates.ExecuteTemplate(w, tmpl+".html", p); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

//URL validation for basic web services
var validPath = regexp.MustCompile("^/$|/(home|about)/(|[a-zA-Z0-9]+)$")

func validate(
    fn func(
        http.ResponseWriter,
        *http.Request,
    )) http.HandlerFunc {
    return func(
        w http.ResponseWriter,
        r *http.Request,
    ) {
        //log.Printf("Request URL Path %s ", r.URL.Path)
        m := validPath.FindStringSubmatch(r.URL.Path)
        if m == nil {
            http.NotFound(w, r)
            return
        }
        fn(w, r)
    }
}

//Main method to install
func Main() {
    log.Printf("TEST APP SERVER STARTED")

    http.HandleFunc("/", validate(homeHandler))
    http.HandleFunc("/home/", validate(homeHandler))
    http.HandleFunc("/about/", validate(aboutHandler))

    http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
    //http.Handle("/templ/", http.StripPrefix("/templ/", http.FileServer(http.Dir("templ"))))
    if *addr {
        l, err := net.Listen("tcp", "127.0.0.1:0")
        if err != nil {
            log.Fatal(err)
        }
        err = ioutil.WriteFile("final-port.txt", []byte(l.Addr().String()), 0644)
        if err != nil {
            log.Fatal(err)
        }
        s := &http.Server{}
        s.Serve(l)
        return
    }

    http.ListenAndServe(":8080", nil)
}

When I start the server.go directly it works [by making Main() in server.go as main() and go run server.go]. But when I use the above structure it fails.

Error:

panic: open about.html: no such file or directory

goroutine 1 [running]:
html/template.Must(0x0, 0x81a568, 0x11980f20, 0x0)
    /usr/local/go/src/html/template/template.go:304 +0x40
github.com/dineshappavoo/test-proj/app.init()
    /Users/Dinesh/go/src/github.com/dineshappavoo/test-proj/app/server.go:625 +0x1ec
main.init()
    /Users/Dinesh/go/src/github.com/dineshappavoo/test-proj/main.go:9 +0x39

EDIT-I I gave the absolute path for html templates. It worked. But css is not loading. I changed the following line.

http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("/app/"))))

I am new to go language. Could anyone help me on this?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀
    • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100