使用GoLang Web服务器提供静态内容 [英] Serving static content with GoLang Webserver

查看:266
本文介绍了使用GoLang Web服务器提供静态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在探索Go的深度,并且我一直在尝试编写一个简单的Web应用程序来包装我的头部。我试图为React.js应用程序提供服务。



以下是Go服务器的代码。我有 / 服务于 index.html 这个工作正常的默认路由。我努力让静态文件被提供给该索引文件。虽然我需要静态地提供JavaScript / CSS / Media文件,但我允许React应用程序执行它自己的客户端路由功能。



例如,我需要能够将 bundle.js 文件放入 index.html 中以供React应用程序运行。目前,当我路由到 localhost:8000 / dist / 时,我看到列出的文件,但是从那里点击的每个文件/文件夹都会抛出 404页面未找到。有什么我失踪了吗?向正确的方向推进将不胜感激。

Webserver.go

  







$ bgithub.com/BurntSushi/toml
github.com/gorilla/mux


类型ServerConfig结构{
环境字符串
主机字符串
HttpPort int
HttpsPort int
ServerRoot字符串
StaticDirectories []字符串
}

func ConfigureServer()ServerConfig {
_,err:= os.Stat(env.toml)
if err!= nil {
log.Fatal(Config file is missing:env.toml)
}

var config ServerConfig
if _,err:= toml.DecodeFile(env.toml,& config); err!= nil {
log.Fatal(err)
}

return config
}

func IndexHandler(w http.ResponseWriter ,r * http.Request){
http.ServeFile(w,r,./src/index.html)
}

func main(){
Config:= ConfigureServer()
router:= mux.NewRouter()

//配置要提供的静态内容。
router.Handle(/ dist /,http.StripPrefix(/ dist /,http.FileServer(http.Dir(dist))))

//路由到客户端应用程序。
router.HandleFunc(/,IndexHandler).Methods(GET)

log.Printf(fmt.Sprintf(在主机%s上启动HTTP服务器:%d。 ,Config.Host,Config.HttpPort))

if err:= http.ListenAndServe(fmt.Sprintf(%s:%d,Config.Host,Config.HttpPort),router); err!= nil {
log.Fatal(err)
}
}


解决方案

根据 gorilla mux docs ,正确的方法是使用 PathPrefix 注册的处理程序,如下所示: router.PathPrefix(/ dist /)。Handler(http.StripPrefix(/ dist /,http.FileServer(http.Dir(dist))))

如果您在文档中搜索类似于 PathPrefix(/ static /)的文档,可以找到一个示例






这种通配符行为实际上默认使用net / http中的模式匹配机制,所以如果你不使用大猩猩,但只是默认的净/ HTTP,你可以做到以下几点:

  http。 Handle(/ dist /,http.StripPrefix(/ dist /,http.FileServer(http.Dir(dist))))


I'm exploring the depths of Go, and I've been trying to write a simple web application to wrap my head around everything. I'm trying to serve a React.js application.

Below is the code of the Go server. I've got the default route of / serving the index.html which is working fine. I'm struggling to allow static files to be served to that index file. I'm allowing the React App to do it's own client side routing, although I need to statically serve the JavaScript / CSS / Media files.

For example, I need to be able to serve the bundle.js file into the index.html for the React application to run. Currently, when I route to localhost:8000/dist/ I see the files being listed, but every file/folder that I click from there is throwing a 404 Page Not Found. Is there something that I'm missing? A push in the right direction would be greatly appreciated.

Webserver.go

package main

import (
    "net/http"
    "log"
    "fmt"
    "os"

    "github.com/BurntSushi/toml"
    "github.com/gorilla/mux"
)

type ServerConfig struct {
    Environment string
    Host string
    HttpPort int
    HttpsPort int
    ServerRoot string
    StaticDirectories []string
}

func ConfigureServer () ServerConfig {
    _, err := os.Stat("env.toml")
    if err != nil {
        log.Fatal("Config file is missing: env.toml")
    }

    var config ServerConfig
    if _, err := toml.DecodeFile("env.toml", &config); err != nil {
        log.Fatal(err)
    }

    return config
}

func IndexHandler (w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./src/index.html")
}

func main () {
    Config := ConfigureServer()
    router := mux.NewRouter()

    // Configuring static content to be served.
    router.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))

    // Routing to the Client-Side Application.
    router.HandleFunc("/", IndexHandler).Methods("GET")

    log.Printf(fmt.Sprintf("Starting HTTP Server on Host %s:%d.", Config.Host, Config.HttpPort))

    if err := http.ListenAndServe(fmt.Sprintf("%s:%d", Config.Host, Config.HttpPort), router); err != nil {
        log.Fatal(err)
    }
}

解决方案

Per the gorilla mux docs, the proper way to do this would be a handler registered with PathPrefix, like this:

router.PathPrefix("/dist/").Handler(http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))

An example can be found if you search the docs for something like PathPrefix("/static/").


This wildcard behavior actually comes by default with the pattern matching mechanism in net/http, so if you weren't using gorilla, but just the default net/http, you could do the following:

http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))

这篇关于使用GoLang Web服务器提供静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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