如何在 golang 中使用 html

我正在学习 golang 并尝试制作一个简单的网站。这是我的文件夹结构。


- ui

   |

   - login.html

- cmd

   |

   - main.go

我的main.go


package main


import (

    "html/template"

    "net/http"

)


var tmpl *template.Template


func init() {

    tmpl = template.Must(template.ParseFiles("../ui/login.html"))

}


func main() {

    http.HandleFunc("/", foo)

    http.ListenAndServe(":8080", nil)

}


func foo(reswt http.ResponseWriter, req *http.Request) {

    tmpl.ExecuteTemplate(reswt, "../ui/login.html", nil)


}

login.html


<html>

    <form method="POST">

        <label for="uname">User Name</label>

        <input type="text" id="uname" name="username">

        <br>


        <input type="submit">


    </form>

</html>

当我执行时main.go,我没有收到错误。但什么也没有localhost:8080。


如果我保留main.go相同login.html的文件夹,这有效。


为什么这个文件夹结构不起作用?我已经尝试过[this SO thread],但这并不能解决我的问题1


添加后的以下部件css不起作用。


<style>

input[type=submit]:active {

  background: #cde5ef;

  border-color: #9eb9c2 #b3c0c8 #b4ccce;

  -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);

  box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);

}


</style>



<div class="login">

  <h1>Login to Web App</h1>

  <form method="post" action="">

    <p><input type="text" name="login" value="" placeholder="Username or Email"></p>

    <p><input type="password" name="password" value="" placeholder="Password"></p>

    <p class="remember_me">

      <label>

        <input type="checkbox" name="remember_me" id="remember_me">

        Remember me on this computer

      </label>

    </p>

    <p class="submit"><input type="submit" name="commit" value="Login"></p>

  </form>

</div>


<div class="login-help">

  <p>Forgot your password? <a href="#">Click here to reset it</a>.</p>

</div>


慕尼黑的夜晚无繁华
浏览 96回答 2
2回答

繁星点点滴滴

ParseFiles将文件列表的名称存储为模板名称。这意味着,在您的情况下,login.html应该在执行中使用,而 while../ui/login.html不可用。这是可行的,因为 login.html 已经被命名为init()。func init() {&nbsp; &nbsp; tmpl = template.Must(template.ParseFiles("../ui/login.html"))}func foo(reswt http.ResponseWriter, req *http.Request) {&nbsp; &nbsp; tmpl.ExecuteTemplate(reswt, "login.html", nil)}

繁星淼淼

对于泛型类型,您可以这样调用import("html/template")// output htmlfunc OutputHTML(w http.ResponseWriter, filename string, data interface{}) {&nbsp; &nbsp;t, err := template.ParseFiles(filename)&nbsp; &nbsp;if err != nil {&nbsp; &nbsp; &nbsp; &nbsp;http.Error(w, err.Error(), 500)&nbsp; &nbsp; &nbsp; &nbsp;return&nbsp; &nbsp;}&nbsp; &nbsp;if err := t.Execute(w, data); err != nil {&nbsp; &nbsp; &nbsp; &nbsp;http.Error(w, err.Error(), 500)&nbsp; &nbsp; &nbsp; &nbsp;return&nbsp; &nbsp;}}你这样称呼它OutputHTML(w, "anyhtmlfile.html",nil)
打开App,查看更多内容
随时随地看视频慕课网APP