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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler