首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用GoLang with服务器服务静态内容

使用GoLang with服务器服务静态内容
EN

Stack Overflow用户
提问于 2017-05-12 17:04:07
回答 2查看 2.5K关注 0票数 4

我正在探索Go的深度,我一直在尝试编写一个简单的web应用程序来解决所有的问题。我正在尝试提供一个React.js应用程序。

下面是Go服务器的代码。我已经得到了/index.html服务的默认路径,它运行良好。我很难允许静态文件被送达到那个索引文件中。我允许React完成它自己的客户端路由,尽管我需要静态地服务JavaScript / CSS / Media文件。

例如,我需要能够将bundle.js文件服务到index.html中,这样才能运行React应用程序。目前,当我路由到localhost:8000/dist/时,我会看到列出的文件,但是我从那里单击的每个文件/文件夹都会抛出一个404 Page Not Found。我遗漏了什么吗?如果能朝正确的方向推进,我们将不胜感激。

Webserver.go

代码语言:javascript
复制
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)
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-12 18:01:48

根据大猩猩医学博士,正确的方法是在PathPrefix中注册一个处理程序,如下所示:

代码语言:javascript
复制
router.PathPrefix("/dist/").Handler(http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))

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

这种通配符行为实际上是在默认情况下与net/http中的模式匹配机制一起使用的,因此,如果您没有使用大猩猩,但只使用默认的net/http,则可以执行以下操作:

代码语言:javascript
复制
http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))
票数 2
EN

Stack Overflow用户

发布于 2017-05-12 17:10:42

文件访问路径可能会出现问题。尝试:

代码语言:javascript
复制
// Strip away "/dist" instead of "/dist/"
router.Handle("/dist/", http.StripPrefix("/dist", http.FileServer(http.Dir("dist"))))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43943038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档