在Go模板中包含js文件 [英] Include js file in Go template

查看:82
本文介绍了在Go模板中包含js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  / * tick-tock.go * / 
包裹主

导入(
fmt
io / ioutil
log
net / http


//内容为主html页面。
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;
颜色:#2B1B17;
text-shadow:1px 1px#E5E4E2;
背景:#FFFFFF;
}
< / style>
< / head>
< body>
< h2 align = center> Go Timer< / h2>
< div id =outputstyle =width:30%; height:63%; overflow-y:scroll; float:left;>< / div>
< div id =v1style =width:50%; height:30%; overflow-y:scroll; float:left;>< / div>
< div id =v2style =width:50%; height:30%; overflow-y:scroll; float:left;>< / div>
< input id =setttype =submitname =settvalue =Settingsonclick =changeUrl()>

< script type =text / javascript>

var myDelay;
$ b $(document).ready(function()
{
$(#output)。append(Waiting for system time ..);

myDelay = setInterval(delayedPost(),1000);

});

函数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);
});
}

函数delayedPost1()
{
$ .post(http:// localhost:9999 / dev,,function(data,status )
{
$(#output)。prepend(data);
});
$ b $ .post(http:// localhost:9999 / v1,,function(data,status)
{
$(#v1)。 prepend(data);
});
$ b $ .post(http:// localhost:9999 / v3,,function(data,status)
{
$(#v2)。 prepend(data);
});


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



}

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

//主页面的处理程序。
func处理程序(w http.ResponseWriter,r * http.Request){
fmt.Fprint(w,page)
}

//处理程序以迎合AJAX请求
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(/
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,Could not 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编程,也没有编写完整的代码。所以请尝试解释很简单。提前致谢!

解决方案

您需要 Handler HandlerFunc 将发送文件内容( jquery.min.js

您有3个选项:

手动操作 / h2>

这是更复杂的解决方案。它看起来像在你的处理函数中读取文件的内容,设置适当的响应内容类型( application / javascript )并发送内容(<

注意事项:阅读文件时,必须指定一个绝对路径(例如$ c> [] byte )。路径。如果您指定了相对路径,请确保该文件位于您启动应用程序的当前文件夹(工作目录)中。



示例:

  func SendJqueryJs(w http.ResponseWriter,r * http.Request){
data,err:= ioutil.ReadFile(jquery.min。 js)
如果err!= nil {
http.Error(w,Could not 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))
}

上面的例子只能提供一个文件: jquery.min.js

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

code>



利用 http.serveFile()



这很容易:函数< a href =http://golang.org/pkg/net/http/#ServeFile =nofollow noreferrer> http.ServeFile() 能够将一个文件的内容发送到指定的响应。您仍然需要创建一个函数或处理函数来使用它,但它会为您完成剩下的工作:

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



利用 http.FileServer()



如果你需要提供多个静态文件,这是 FileServer() code> 函数很方便,它会返回一个 Handler ,它会自动提供来自本地文件系统的文件,它们是您指定的根文件夹的后代。 / p>

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



示例:

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

这会注册一个 Handler / tmpfiles / 文件夹中的本地文件系统中找到的文件。因此,例如以下< script> 链接:

 < script type =text / javascriptsrc =/ tmpfiles / jquery.min.js> 

会得到 /tmp/jsquery.min.js

查看这个答案,详细说明如何使用/启动一个静态文件服务器


I started learning Go recently. I got a sample like as web app. I have:

/* 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)
}

I couldn't load local jquery.min.js. When I wrote src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" it was loaded. How can I load local js file? I am not good at coding in Go and I did not write full code. So please try to explain very simple. Thanks in advance!

解决方案

You need a Handler or a HandlerFunc which will send the file content (jquery.min.js) to the web browser when requested.

You have 3 options:

Doing It Manually

This is the more complex solution. It would look like in your handler function you read the content of the file, set proper response content type (application/javascript) and send the content (which is a []byte) to the response.

Things to look out for: When reading the file, you have to specify an absolute path. If you specify a relative path, be sure the file is in the current folder (working directory) you start your app from.

Example:

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))
}

The above example is capable of serving only 1 file: jquery.min.js for the request:

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

Utilizing http.ServeFile()

This is much easier: The function http.ServeFile() is capable of sending the content of one file to the specified response. You still need to create a function or handler to use it, but it does the rest for you:

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

Utilizing http.FileServer()

If you need to serve multiple static files, this is where FileServer() function comes handy which returns you a Handler which automatically serves files from your local file system that are descendants of the root folder you specify.

This solution is much more flexible: it can send many files of multiple types, detects and sets content type automatically. The handler is also capable of rendering HTML pages for listing directory content with links to the files and to parent/child folders.

Example:

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

This will register a Handler at the URL /tmpfiles/ which serves files found in your local filesystem in the /tmp folder. So for example the following <script> link:

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

Will get the /tmp/jsquery.min.js file from the server.

Check out this answer which details how to use/fire up a Static File Server.

这篇关于在Go模板中包含js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆