为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 golang 中使用 html

如何在 golang 中使用 html

Go
慕尼黑的夜晚无繁华 2023-07-10 10:06:33
我正在学习 golang 并尝试制作一个简单的网站。这是我的文件夹结构。- ui   |   - login.html- cmd   |   - main.go我的main.gopackage mainimport (    "html/template"    "net/http")var tmpl *template.Templatefunc 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>
查看完整描述

2 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

ParseFiles将文件列表的名称存储为模板名称。这意味着,在您的情况下,login.html应该在执行中使用,而 while../ui/login.html不可用。


这是可行的,因为 login.html 已经被命名为init()。


func init() {

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

}


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

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

}


查看完整回答
反对 回复 2023-07-10
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

对于泛型类型,您可以这样调用


import(

"html/template"

)

// output html

func OutputHTML(w http.ResponseWriter, filename string, data interface{}) {

   t, err := template.ParseFiles(filename)

   if err != nil {

       http.Error(w, err.Error(), 500)

       return

   }

   if err := t.Execute(w, data); err != nil {

       http.Error(w, err.Error(), 500)

       return

   }

}

你这样称呼它


OutputHTML(w, "anyhtmlfile.html",nil)


查看完整回答
反对 回复 2023-07-10
  • 2 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信