aboutsummaryrefslogtreecommitdiff
path: root/src/server/spa.go
blob: 1dd1e96bba8f2cef3bb4729618aaab21a3f5d9dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
	"net/http"
	"os"
	"path/filepath"
)

// https://github.com/gorilla/mux#serving-single-page-applications
type spaHandler struct {
	staticPath string
}

func (h spaHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	path, err := filepath.Abs(request.URL.Path)
	if err != nil {
		http.Error(writer, err.Error(), http.StatusBadRequest)
	}

	path = filepath.Join(h.staticPath, path)
	if _, err = os.Stat(path); os.IsNotExist(err) {

		serve_path := filepath.Base(path)
		if len(filepath.Ext(path)) == 0 {
			serve_path = "index.html"
		}
		serve_path = filepath.Join(h.staticPath, serve_path)

		http.ServeFile(writer, request, serve_path)
		return
	} else if err != nil {
		http.Error(writer, err.Error(), http.StatusInternalServerError)
		return
	}

	http.FileServer(http.Dir(h.staticPath)).ServeHTTP(writer, request)
}