douchong8393 2017-05-12 17:04
浏览 62
已采纳

使用GoLang Web服务器提供静态内容

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)
    }
}
  • 写回答

2条回答 默认 最新

  • douanye8442 2017-05-12 18:01
    关注

    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"))))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?