简体   繁体   English

如何在Go服务器上运行html

[英]How to run html on a Go server

I've created a server in Go and I'm trying to run an html file in the browser. 我已经在Go中创建了服务器,并且试图在浏览器中运行html文件。 But the browser just prints out the code like a txt file instead of rendering the html formatting. 但是浏览器只是像txt文件一样打印出代码,而不是呈现html格式。 My index.html file is saved in the /public directory. 我的index.html文件保存在/ public目录中。

My go code looks like this: 我的go代码如下所示:

package main

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

func main() {
    http.Handle("/", new(MyHandler))

    http.ListenAndServe(":8000", nil)
}

type MyHandler struct {
    http.Handler
}

func (this *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    path := "public/" + req.URL.Path
    data, err := ioutil.ReadFile(string(path))

    if err == nil {
        w.Write(data)
    } else {
        w.WriteHeader(404)
        w.Write([]byte("404 - " + http.StatusText(404)))
    }

}

In your main try using http.HandleFunc("/", ServeHTTP) then edit the ServeHTTP method so it doesn't have a reciever ie; 在您的主要尝试中,使用http.HandleFunc("/", ServeHTTP)然后编辑ServeHTTP方法,使其不具有ServeHTTP即; func ServeHTTP(w http.ResponseWriter, req *http.Request)

You attempt to use that object and the Handle method may work fine too (if implemented correctly) but most of the examples use HandleFunc and if you do as well I bet your problem will go away. 您尝试使用该对象,并且Handle方法也可以正常工作(如果正确实现),但是大多数示例都使用HandleFunc ,如果您也这样做,我敢打赌,您的问题将会消失。

The only other thing that would be causing the issues you're observing is a failure to read the file who's contents are assigned to data or some misconception about what the data in that file actually is. 引起您所观察到的问题的唯一另一件事是无法读取文件的内容,该文件的内容已分配给data或者对文件中的实际data有误解。

Right now you're just reading the contents of the file and writing it out. 现在,您只是在读取文件内容并将其写出。 Since Go can't tell what type of file it is, it can't set the header. 由于围棋说不出它是什么类型的文件,它不能设置标题。

Thankfully, there's a useful http.ServeFile function in the net/http package that can help you. 幸运的是, net / http软件包中有一个有用的http.ServeFile函数可以为您提供帮助。

func (this *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    path := "public/" + req.URL.Path
    http.ServeFile(w, r, filepath.Join("path/to/file", path))
}

http.ServeFile attempts to set the Content-Type based on the file extension or first handful of bytes (for a HTML file it should get it right). http.ServeFile尝试根据文件扩展名或前几个字节来设置Content-Type (对于HTML文件,它应该正确http.ServeFile )。

A better solution is to make your route handler the http.FileServer 更好的解决方案是使路由处理程序成为http.FileServer

func main() {
    http.Handle("/", http.FileServer(http.Dir("./public"))

    http.ListenAndServe(":8000", nil)
}

Take a look at the examples in the Go docs for how to use it in other ways. 查看Go文档中的示例,了解如何以其他方式使用它。

Shameless plug: I wrote a small middleware library that makes it a bit easier to serve static files in Go that you may find use in (or read just read the code for insight): https://github.com/elithrar/station 无耻的插件:我写了一个小的中间件库,使在Go中提供静态文件(您可能会在其中使用)更容易一些(或只需阅读一下代码即可获得洞察力): https : //github.com/elithrar/station

Start with getting the HTML up and running. 首先启动并运行HTML。 Then, build in your HTTP error handling (eg 404). 然后,构建您的HTTP错误处理(例如404)。 I recommend using the text/template from the start, even if you're not adding any dynamism to your app... yet! 我建议从一开始就使用text/template ,即使您尚未向应用程序添加任何动力……

package main

import (
    "io/ioutil"
    "log"
    "net/http"
    "text/template"
)

func main() {
    http.HandleFunc("/", RootHandler)

    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

func RootHandler(res http.ResponseWriter, req *http.Request) {
    file, _ := ioutil.ReadFile("public/index.html")
    t := template.New("")
    t, _ = t.Parse(string(file))

    t.Execute(res, nil)
}

In case you want to hold off on using the text/template package and just serve the HTML straight up, simply read your index.html file and write it to the response writer (eg res for response in my example, however many folks also use w for writer). 如果您想推迟使用text/template包并直接提供HTML,只需阅读index.html文件并将其写入响应编写器(例如,在我的示例中为res的响应,但是许多人也使用w (作家)。

package main

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

func main() {
    http.HandleFunc("/", RootHandler)

    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

func RootHandler(res http.ResponseWriter, req *http.Request) {
    file, _ := ioutil.ReadFile("public/index.html")
    res.Write(file)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM