douqiao7188 2016-01-18 23:27
浏览 49
已采纳

使用go net / http mux服务单页应用程序

I'm building an api that also serves my react front end app, but am having an issue serving my index.html

Given that it's not really a go template I'm not using html/template.

I'm not seeing a strait forward way to serve the static html root of my app on all pages that do not start /api in the route.

I'm purposely trying not to use any go frameworks beyond gorilla's mux

My handler.go:

func Index(w http.ResponseWriter, r *http.Request) {
    http.FileServer(http.Dir("./views"))
}

Routes.go:

type Route struct {
    Name        string
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

var routes = Routes{
    Route{
        "Index",
        "GET",
        "/",
        Index,
    },
}

router.go

import (
    "net/http"

    "github.com/gorilla/mux"
)

func NewRouter() *mux.Router {

    router := mux.NewRouter().StrictSlash(true)
    for _, route := range routes {
        var handler http.Handler

        handler = route.HandlerFunc
        handler = Logger(handler, route.Name)

        router.
            Methods(route.Method).
            Path(route.Pattern).
            Name(route.Name).
            Handler(handler)

    }

    return router
}

main:

package main

import (
    "./server"
    "log"
    "net/http"
)

func main() {

    router := server.NewRouter()

    log.Fatal(http.ListenAndServe(":8080", router))
}

Currently a blank page shows up, and thats it. My index.html is located in /views/index.html in relation to the executable (but I've tried it in relation to the handler as well)

Update

I was able to serve the html file using the method shown in this question: How do you serve a static html file using a go web server? However using mux and the more modularized file structure still yields a nice pretty, clean blank page.

  • 写回答

1条回答 默认 最新

  • douren6874 2016-01-19 00:11
    关注

    In handler.go, your Index function is actually a no-op, since http.FileServer() returns a Handler, which is never passed the ResponseWriter or Request, hence the blank page.

    Maybe try something like this to at least get past that:

    func Index(w http.ResponseWriter, r *http.Request) {
        http.FileServer(http.Dir("./views")).ServeHTTP(w, r)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大