【问题标题】:Include js file in Go template在 Go 模板中包含 js 文件
【发布时间】:2015-05-08 02:39:10
【问题描述】:

我最近开始学习围棋。我得到了一个像网络应用程序一样的样本。我有:

/* tick-tock.go */
package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

// Content for the main html page..
var page = `<html>
           <head>
             <script type="text/javascript"
               src="http://localhost:8081/jquery.min.js">
             </script>
             <style> 
               div {
                 font-family: "Times New Roman", Georgia, Serif;
                 font-size: 1em;
                 width: 13.3em;
                 padding: 8px 8px; 
                 border: 2px solid #2B1B17;
                 color: #2B1B17;
                 text-shadow: 1px 1px #E5E4E2;
                 background: #FFFFFF;
               }
             </style>
           </head>
           <body>
             <h2 align=center>Go Timer </h2>
             <div id="output" style="width: 30%; height: 63%; overflow-y: scroll; float:left;"></div>
             <div id="v1" style="width: 50%; height: 30%; overflow-y: scroll; float:left;"></div>
             <div id="v2" style="width: 50%; height: 30%; overflow-y: scroll; float:left;"></div>
             <input id="sett" type="submit" name="sett" value="Settings" onclick="changeUrl()">

             <script type="text/javascript">

               var myDelay;

               $(document).ready(function () 
               {
                   $("#output").append("Waiting for system time..");

                   myDelay = setInterval("delayedPost()", 1000);               

                });

               function delayedPost() 
               {
                 $.post("http://localhost:9999/dev", "", function(data, status) 
                 {
                    //$("#output").empty();
                    $("#output").prepend(data);
                 });

                 $.post("http://localhost:9999/v1", "", function(data, status) {
                    //$("#output").empty();
                    $("#v1").prepend(data);
                 });

                 $.post("http://localhost:9999/v2", "", function(data, status) {
                    //$("#output").empty();
                    $("#v2").prepend(data);
                 });
               }

               function delayedPost1() 
               {
                 $.post("http://localhost:9999/dev", "", function(data, status) 
                 {                    
                    $("#output").prepend(data);
                 });

                 $.post("http://localhost:9999/v1", "", function(data, status) 
                 {                   
                    $("#v1").prepend(data);
                 });

                 $.post("http://localhost:9999/v3", "", function(data, status) 
                 {                    
                    $("#v2").prepend(data);
                 });
               }

               function changeUrl()
               {
                  alert('salom');                      
                  clearInterval(myDelay);



               }

             </script>
           </body>
         </html>`

// handler for the main page.
func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, page)
}

// handler to cater AJAX requests
func handlerDevs(w http.ResponseWriter, r *http.Request) {
    //fmt.Fprint(w, time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST"))
    fmt.Fprint(w, "<font color=red>Dev1<br></font>")
}

func handlerV1(w http.ResponseWriter, r *http.Request) {
    //fmt.Fprint(w, time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST"))
    fmt.Fprint(w, "<font color=blue>Vertical1<br></font>")
}

func handlerV2(w http.ResponseWriter, r *http.Request) {
    //fmt.Fprint(w, time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST"))
    fmt.Fprint(w, "<font color=green>Vertical2<br></font>")
}

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/dev", handlerDevs)
    http.HandleFunc("/v1", handlerV1)
    http.HandleFunc("/v2", handlerV2)
    log.Fatal(http.ListenAndServe(":9999", nil))
    http.HandleFunc("/jquery.min.js", SendJqueryJs)
    panic(http.ListenAndServe(":8081", nil))
}
func SendJqueryJs(w http.ResponseWriter, r *http.Request) {
    data, err := ioutil.ReadFile("jquery.min.js")
    if err != nil {
        http.Error(w, "Couldn't read file", http.StatusInternalServerError)
        return
    }
    w.Header().Set("Content-Type", "application/javascript")
    w.Write(data)
}

我无法加载本地 jquery.min.js。当我写src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" 时,它被加载了。如何加载本地 js 文件?我不擅长用 Go 编码,也没有写完整的代码。所以请尽量解释的很简单。提前致谢!

【问题讨论】:

  • 我会尝试的第一件事是将/jquery.min.js 更改为jquery.min.js

标签: jquery go webserver


【解决方案1】:

您需要 HandlerHandlerFunc,它们会在请求时将文件内容 (jquery.min.js) 发送到网络浏览器。

您有 3 个选项:

手动操作

这是更复杂的解决方案。看起来就像在您的处理函数中读取文件的内容,设置正确的响应内容类型 (application/javascript) 并将内容(即 []byte)发送到响应。

注意事项:读取文件时,必须指定绝对路径。如果您指定相对路径,请确保该文件位于您启动应用程序的当前文件夹(工作目录)中。

例子:

func SendJqueryJs(w http.ResponseWriter, r *http.Request) {
    data, err := ioutil.ReadFile("jquery.min.js")
    if err != nil {
        http.Error(w, "Couldn't read file", http.StatusInternalServerError)
        return
    }
    w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
    w.Write(data)
}

func main() {
    http.HandleFunc("/jquery.min.js", SendJqueryJs)
    panic(http.ListenAndServe(":8081", nil))
}

上面的示例只能为请求提供 1 个文件:jquery.min.js

http://localhost:8081/jquery.min.js

利用http.ServeFile()

这要容易得多:函数http.ServeFile() 能够将一个文件的内容发送到指定的响应。您仍然需要创建一个函数或处理程序来使用它,但它会为您完成其余的工作:

func SendJqueryJs(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "jquery.min.js")
}

利用http.FileServer()

如果您需要提供多个静态文件,这就是 FileServer() 函数派上用场的地方,它会返回一个 Handler,它会自动提供来自本地文件系统的文件,这些文件是您指定的根文件夹的后代。

这个解决方案更加灵活:它可以发送多种类型的文件,自动检测和设置内容类型。该处理程序还能够呈现 HTML 页面,以列出目录内容以及指向文件和父/子文件夹的链接。

例子:

http.Handle("/tmpfiles/",
    http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

这将在 URL /tmpfiles/ 上注册一个 Handler,它提供在 /tmp 文件夹中的本地文件系统中找到的文件。比如下面的&lt;script&gt;链接:

<script type="text/javascript" src="/tmpfiles/jquery.min.js">

将从服务器获取/tmp/jsquery.min.js 文件。

查看此答案,其中详细说明了如何使用/启动 Static File Server

【讨论】:

  • 它不断收到消息:“从文件系统提供服务?将您的文件添加到工作区。less 如果您将文件添加到您的 DevTools 工作区,您的更改将持久保存到磁盘。将文件夹添加到工作区,将其拖放到 Sources 面板中。有关工作区的更多信息,请参阅工作区文档。"
猜你喜欢
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-05
  • 1970-01-01
相关资源
最近更新 更多