Golang + Angular
Я начал работать с Go и Angular, но у меня странная проблема. Наверное, мне просто не хватает крошечной детали, но я не могу понять.
Я использую https://github.com/julienschmidt/httprouter в качестве маршрутизатора для Go... теперь с Angular, я должен иметь возможность копировать и вставьте URL-адрес в браузер, а Angular должен обрабатывать соответствующие маршруты, правильно?
У меня есть маршрут "/login". Что работает, если маршрут получает доступ через интерфейс... но не, если я введу "mypage.com/login" в браузер, получив 404.
Go routing в основном делает только
router.NotFound = http.FileServer(http.Dir("./public"))
Что работает для маршрута "/", но не для чего-либо еще. Кажется, это правильно. Но как правильно настроить маршрутизацию, поэтому Angular обрабатывает всю маршрутизацию?
Ответы
Ответ 1
Это то, что я использую со стандартной библиотекой Go, и маршрутизация отлично работает.
Проверьте функцию Adapt здесь
// Creates a new serve mux
mux := http.NewServeMux()
// Create room for static files serving
mux.Handle("/node_modules/", http.StripPrefix("/node_modules", http.FileServer(http.Dir("./node_modules"))))
mux.Handle("/html/", http.StripPrefix("/html", http.FileServer(http.Dir("./html"))))
mux.Handle("/js/", http.StripPrefix("/js", http.FileServer(http.Dir("./js"))))
mux.Handle("/ts/", http.StripPrefix("/ts", http.FileServer(http.Dir("./ts"))))
mux.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("./css"))))
// Do your api stuff**
mux.Handle("/api/register", util.Adapt(api.RegisterHandler(mux),
api.GetMongoConnection(),
api.CheckEmptyUserForm(),
api.EncodeUserJson(),
api.ExpectBody(),
api.ExpectPOST(),
))
mux.HandleFunc("/api/login", api.Login)
mux.HandleFunc("/api/authenticate", api.Authenticate)
// Any other request, we should render our SPA only html file,
// Allowing angular to do the routing on anything else other then the api
// and the files it needs for itself to work.
// Order here is critical. This html should contain the base tag like
// <base href="/"> *href here should match the HandleFunc path below
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "html/index.html")
})
Ответ 2
Вы можете напрямую использовать пакет http
.
Страница указателя
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./public/index.html")
})
Это будет файл index.html для всех запросов, которые не соответствуют маршруту.
Файловый сервер
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
Это будет обслуживать все файлы из общего каталога.
Не забудьте запустить сервер
http.ListenAndServe(":8000", nil)
Ответ 3
использовать goji micro framwork
https://github.com/zenazn/goji
Легко использовать
func render_html_page(w http.ResponseWriter, url string) {
t, err := template.ParseFiles(url)
if err != nil {
panic (err)
}
t.Execute(w, nil)
}
func index(c web.C, w http.ResponseWriter, r *http.Request) {
render_html_page(w, "./public/index.html")
}
func main() {
goji.Get("/", index)
goji.Serve()
}
этот код работает, вам нужно просто импортировать
Ответ 4
У меня была точная 404 проблема. Эта маршрутизация - html5mode. Вам нужно указать обработчики в вашем приложении .yaml. Проверьте мою версию проекта Tour of Heroes здесь https://github.com/nurp/angular2-tour-of-heroes
добавив это в ваше приложение. yaml может решить проблему.
- url: /.*
static_files: index.html
upload: index.html
Ответ 5
Пожалуйста, определите обработчик router.Notfound для обслуживания углового файла index.html.
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func angularHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./public/index.html")
}
func main() {
router := httprouter.New()
// handle angular
router.NotFound = http.HandlerFunc(angularHandler)
// serve static files
router.ServeFiles("/*filepath", http.Dir("./public"))
log.Fatal(http.ListenAndServe(":3000", router))
}