Golang 的静态文件服务器,用于为 Vue.js 应用程序提供服务

ami*_*nab 7 go vue.js

我想创建一个简单的文件服务器来GoVue.js应用程序的静态文件提供服务。

默认情况下,Vue.js使用npm run dev或有自己的运行器npm run build

问题的关键是,当我运行Vue.js其自己的刀具系统的应用程序,它回落404 errorindex.html。所以Vue-router可以处理剩下的。

我该如何处理Go

我尝试了httprouter它的NotFound方法,如文档所述,但如果Router.

Anu*_*dha 7

假设文件夹结构如下

在此处输入图片说明

您可以使用以下 golang 代码来提供静态文件。我添加了一个额外的 api 来展示我们如何拥有它。gorilla-mux用于 URL 路由。

我已经将构建的发行版通过 golang 提供服务。而index.html看起来像这样

<!DOCTYPE html>
<html>

<head>
  <meta charset=utf-8>
  <link rel=stylesheet href=static/normalize.css>
  <title>vue-spa</title>
  <link href=./static/css/app.6fde27bf4e24b3395514fd5ee0329156.css rel=stylesheet>
</head>

<body>
  <div id=app></div>
  <script type=text/javascript src=./static/js/manifest.6fd2c38fc83e93a893ff.js></script>
  <script type=text/javascript src=./static/js/vendor.bc5a61acb9e2b4c6e037.js></script>
  <script type=text/javascript src=./static/js/app.c8f0b049292d256d1e93.js></script>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

请注意,它是静态文件的基础 ./static

package main

import (
    "encoding/json"
    "net/http"
    "os"
    "time"
    "log"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    // It's important that this is before your catch-all route ("/")
    api := r.PathPrefix("/api/").Subrouter()
    api.HandleFunc("/users", GetUsersHandler).Methods("GET")
    // Serve static assets directly.
    r.PathPrefix("/static").Handler(http.FileServer(http.Dir("dist/")))
    // Catch-all: Serve our JavaScript application's entry-point (index.html).
    r.PathPrefix("/").HandlerFunc(IndexHandler("dist/index.html"))


srv := &http.Server{
        Handler: handlers.LoggingHandler(os.Stdout, r),
        Addr:    "127.0.0.1:8088",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }
    log.Fatal(srv.ListenAndServe())
}

func IndexHandler(entrypoint string) func(w http.ResponseWriter, r *http.Request) {
    fn := func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, entrypoint)
    }
    return http.HandlerFunc(fn)
}

func GetUsersHandler(w http.ResponseWriter, r *http.Request) {
    data := map[string]interface{}{
        "id": "123",
        "timeStamp": time.Now().Format(time.RFC3339),
    }
    b, err := json.Marshal(data)
    if err != nil {
        http.Error(w, err.Error(), 400)
        return
    }
    w.Write(b)
}
Run Code Online (Sandbox Code Playgroud)