summaryrefslogtreecommitdiff
path: root/server/server.go
blob: b066a5ff35dd8c44dbfe55d8a8f720ac2f2bd0e5 (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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package server

import (
	_ "embed"
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/benbusby/farside/db"
	"github.com/benbusby/farside/services"
)

//go:embed index.html
var indexHTML string

//go:embed route.html
var routeHTML string

type indexData struct {
	LastUpdated time.Time
	ServiceList []services.Service
}

type routeData struct {
	InstanceURL string
}

func home(w http.ResponseWriter, r *http.Request) {
	serviceList := db.GetServiceList()
	data := indexData{
		LastUpdated: db.LastUpdate,
		ServiceList: serviceList,
	}

	tmpl, err := template.New("").Parse(indexHTML)
	if err != nil {
		log.Println(err)
		http.Error(w, "Error parsing template", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html")

	err = tmpl.Execute(w, data)
	if err != nil {
		log.Println(err)
		http.Error(w, "Error executing template", http.StatusInternalServerError)
	}
}

func state(w http.ResponseWriter, r *http.Request) {
	storedServices := db.GetServiceList()
	jsonData, _ := json.Marshal(storedServices)
	w.Header().Set("Content-Type", "application/json")
	_, _ = w.Write(jsonData)
}

func baseRouting(w http.ResponseWriter, r *http.Request) {
	routing(w, r, false, r.URL.RawQuery)
}

func jsRouting(w http.ResponseWriter, r *http.Request) {
	r.URL.Path = strings.Replace(r.URL.Path, "/_", "", 1)
	routing(w, r, true, r.URL.RawQuery)
}

func routing(w http.ResponseWriter, r *http.Request, jsEnabled bool, query string) {
	value := r.PathValue("routing")
	if len(value) == 0 {
		value = r.URL.Path
	}

	parsedURL, _ := url.Parse(value)
	path := strings.TrimPrefix(parsedURL.Path, "/")
	segments := strings.Split(path, "/")

	if len(segments[0]) == 0 {
		http.Redirect(w, r, "", http.StatusTemporaryRedirect)
	}

	target, err := services.MatchRequest(segments[0])
	if err != nil {
		errMsg := fmt.Sprintf("No routing found for '%s'", segments[0])
		log.Printf("Error during match request: %v\n", err)
		http.Error(w, errMsg, http.StatusBadRequest)
		return
	}

	var servicePath string
	if target == "breezewiki" {
		// Breezewiki requires the subdomain of the instance to be
		// preserved for correct routing
		splitDomain := strings.Split(path, ".")
		if len(splitDomain) > 2 {
			servicePath = strings.Split(path, ".")[0]
		}
	}

	instance, err := db.GetInstance(target, servicePath)
	if err != nil {
		log.Printf("Error fetching instance from db: %v\n", err)
		http.Error(
			w,
			"Error fetching instance for "+target,
			http.StatusInternalServerError)
		return
	}

	if len(segments) > 1 {
		targetPath := strings.Join(segments[1:], "/")
		instance = instance + "/" + targetPath
	}

	w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")

	instance += fmt.Sprintf("?%s", query)
	if jsEnabled {
		data := routeData{
			InstanceURL: instance,
		}
		tmpl, _ := template.New("").Parse(routeHTML)
		w.Header().Set("Content-Type", "text/html")
		_ = tmpl.Execute(w, data)
	} else {
		http.Redirect(w, r, instance, http.StatusFound)
	}
}

func RunServer() {
	mux := http.NewServeMux()
	mux.HandleFunc("/{$}", home)
	mux.HandleFunc("/state/{$}", state)
	mux.HandleFunc("/{routing...}", baseRouting)
	mux.HandleFunc("/_/{routing...}", jsRouting)

	port := os.Getenv("FARSIDE_PORT")
	if len(port) == 0 {
		port = "4001"
	}

	log.Println("Starting server on http://localhost:" + port)

	err := http.ListenAndServe(":"+port, mux)
	if err != nil {
		log.Fatal(err)
	}
}