小编典典

在Go模板中包含js文件

go

我最近开始学习Go。我有一个像网络应用程序这样的示例。我有:

/* 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编写代码,也没有编写完整的代码。因此,请尝试解释非常简单。提前致谢!


阅读 329

收藏
2020-07-02

共1个答案

小编典典

您需要a Handler或a
来在请求时HandlerFunc将文件内容(jquery.min.js)发送到Web浏览器。

您有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"))))

这将Handler在URL处注册一个,该URL
/tmpfiles/服务于在/tmp文件夹中的本地文件系统中找到的文件。因此,例如以下<script>链接:

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

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

2020-07-02