javascript - GO: javascript 和 html MIME 错误

标签 javascript go

我试图在我的 GO 应用程序中加载 javascript,但出现错误:

Resource interpreted as Script but transferred with MIME type text/html:     "http://localhost:4747/twttr.js". localhost/:6
Uncaught SyntaxError: Unexpected token < 

开始:

package main

import (
    "net/http"
    "html/template"
)

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":4747", nil) 
}

func handler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/twttr.js" {
        http.ServeFile(w, r, "twttr.js")
        return
    } 
    t, _ := template.ParseFiles("home.html", "edit.html")
    t.Execute(w, map[string] string {"Title": "My title", "Body": "Hi this is my body"})
}

在我的 HTML 中我有这样的东西:

<!DOCTYPE html>
<html>
<head>
    <title>twitter!</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" src="twttr.js"></script>
<head>

<body>
    <h1>Add new tweet</h1>
    <form action="/save/{{.Title}}" method="get">
    <button type="button" value="addtweet" class="addtweet">Add Tweet!</button>
    </form>
    Title is {{.Title}}
    {{template "edit.html" .}}
</body>
</html>

JS:

 $(document).ready(function(){
    $('.addtweet').click(function(){
        alert("Handler for .click() called.");
    });
})

目录结构:

static/
    home.html
    twttr.js
twttr.go

我认为这与我在 GO 应用程序中显示模板/html 的方式有关。但我不知道确切的问题。我是 GO 和一般编程的新手,所以非常感谢任何指导!

最佳答案

如果您查看 JS 文件加载的结果,它是否是预期的文件?根据发布的代码,我没有看到你处理它,我猜不会。除非你没有发布所有内容。您似乎为每个请求提供相同的结果,包括 JS 文件。

要通过 GO 提供文件,请查看:http://golang.org/pkg/net/http/#ServeFile

您需要检查 URL 并进行相应处理。例如:

if r.URL.Path == "/twttr.js" {
    http.ServeFile(w, r, "static/twttr.js")
    return
} 

t, _ := template.ParseFiles("home.html", "edit.html")
t.Execute(w, map[string] string {"Title": "My title", "Body": "Hi this is my body"}

关于javascript - GO: javascript 和 html MIME 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24982916/

相关文章:

c# - 将 JS 回调函数传递给 C# RT 组件错误 : "Unable to cast object of the type ' mydb. SQLite3JSNoCallback' 到 'mydb.SQLite3JSNoCallback' "

javascript - 遍历嵌套对象/数组

javascript - XmlService 和 importxml 的区别

go - 如何按照Clean Architecture在Golang中实现presenter?

Golang Web Crawler解决方案,2个数据竞争,退出状态66

javascript - 如何处理这个 fetch() 类型错误?

javascript - 如何使用 WebIO 将值从 javascript 发送到 julia?

regex - Go中字符串末尾的正则表达式匹配失败

go - 如何设置仅适用于我的 LAN 网络的 golang 服务器监听器

arrays - 转到文本/模板模板 : how to check value against an array of values within the template itself?