Angular 2 + golang deployment

Hello,
I have recently tried to deploy an angular2 + golang application.
Super simplified sample of code is as follows:

package main

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

func main() {
	fs := http.FileServer(http.Dir("./dist"))
	r := mux.NewRouter()

        // Api routes
        // ....
        // End Api routes

	r.PathPrefix("/").Handler(fs)
	http.ListenAndServe(":8081",r)
}

When the page is refreshed, the request is sent to server which results in a page not found error since the request bypasses the router in angular.
So I’ve concluded that this method is only suitable for static file web sites. Please do correct me if I’m wrong.

Method to try over the weekend.

  • nginx: to serve angular on port 80
  • run golang api server on seperate port(undecided port)

Any suggestions or advice for angular2 + golang web applications? Any norms?

Thanks for feedback.
Edit: grammatical and spelling error. Sorry posting from mobile

The problem with your Go server is that routed apps must fallback to index.html. http.FileServer returns 404 instead.

I would try writing a version of http.Dir that returns the contents of index.html when a file isn’t found. The default implementation isn’t long and should be quick to modify.

2 Likes

Thanks Nathan!! I’ve modified the http.Dir as suggested. Made a struct that implements a modified version of Open function.
New type DirD struct contains string of DirD.Dir and DirD.Def(specifies default file)

Uploaded the code if anyone else is interested.
github.com/dyxj/gomod/blob/master/fs.go

On the topic of NGINX+GO I’ve did a quick search and found the following statement:
Using only Go is better than NGINX+GO(about 30% overhead).
Using only NGINX is better than only Go.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.