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

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")
}