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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题