douzhang2092 2014-07-20 22:07
浏览 16
已采纳

Go + Angular UI路由器

I'm a new Gopher trying to do a Go backend to serve my Angularjs frontend and also serve an API.

This is what I have so far.

package main

import (
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    rtr := mux.NewRouter()
    srtr := rtr.PathPrefix("/api").Subrouter()
    srtr.HandleFunc("/hello", hello).Methods("GET")
    rtr.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))

    http.Handle("/", rtr)

    log.Println("Listening...")
    http.ListenAndServe(":3000", nil)
}

func hello(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello World"))
}

Everything works fine. /api/hello return "Hello World" and if I go to / it will serve my index.html. However since I'm trying to use angular ui-router so I need my go server to send all non-registered routes to angular so angular ui-router can handle them.

For example: If I go /random right now it will return a 404 since I don't have any file under ./static named random. But what I want is Go to forward that request to Angular so ui-router can handle the /random

  • 写回答

1条回答 默认 最新

  • dongzhe6287 2014-10-10 12:47
    关注

    In Your router You should serve index.html to all undefined elsewhere URLs. In mux package there is helpful handler: http://www.gorillatoolkit.org/pkg/mux#Router - look at NotFoundHandler

    You can use it, to handle all 404's and serve index.html instead:

    func main() {
        r := mux.NewRouter()
        r.HandleFunc("/foo", fooHandler)
        r.NotFoundHandler = http.HandlerFunc(notFound)
        http.Handle("/", r)
    
    }
    

    and define notFound function:

    func notFound(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "static/index.html")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b