1
0
Fork 0
mirror of https://github.com/documize/community.git synced 2025-07-22 14:49:42 +02:00

refactored routing/web serving logic

This commit is contained in:
Harvey Kandola 2017-07-21 18:14:19 +01:00
parent 76d77bef9b
commit d888962082
16 changed files with 410 additions and 382 deletions

148
server/routing/entries.go Normal file
View file

@ -0,0 +1,148 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package routing
import (
"net/http"
"github.com/documize/community/core/api"
"github.com/documize/community/core/api/endpoint"
"github.com/documize/community/core/env"
"github.com/documize/community/server/web"
)
// RegisterEndpoints register routes for serving API endpoints
func RegisterEndpoints(rt env.Runtime) {
//**************************************************
// Non-secure routes
//**************************************************
Add(rt, RoutePrefixPublic, "meta", []string{"GET", "OPTIONS"}, nil, endpoint.GetMeta)
Add(rt, RoutePrefixPublic, "authenticate/keycloak", []string{"POST", "OPTIONS"}, nil, endpoint.AuthenticateKeycloak)
Add(rt, RoutePrefixPublic, "authenticate", []string{"POST", "OPTIONS"}, nil, endpoint.Authenticate)
Add(rt, RoutePrefixPublic, "validate", []string{"GET", "OPTIONS"}, nil, endpoint.ValidateAuthToken)
Add(rt, RoutePrefixPublic, "forgot", []string{"POST", "OPTIONS"}, nil, endpoint.ForgotUserPassword)
Add(rt, RoutePrefixPublic, "reset/{token}", []string{"POST", "OPTIONS"}, nil, endpoint.ResetUserPassword)
Add(rt, RoutePrefixPublic, "share/{folderID}", []string{"POST", "OPTIONS"}, nil, endpoint.AcceptSharedFolder)
Add(rt, RoutePrefixPublic, "attachments/{orgID}/{attachmentID}", []string{"GET", "OPTIONS"}, nil, endpoint.AttachmentDownload)
Add(rt, RoutePrefixPublic, "version", []string{"GET", "OPTIONS"}, nil, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(api.Runtime.Product.Version))
})
//**************************************************
// Secure routes
//**************************************************
// Import & Convert Document
Add(rt, RoutePrefixPrivate, "import/folder/{folderID}", []string{"POST", "OPTIONS"}, nil, endpoint.UploadConvertDocument)
// Document
Add(rt, RoutePrefixPrivate, "documents/{documentID}/export", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentAsDocx)
Add(rt, RoutePrefixPrivate, "documents", []string{"GET", "OPTIONS"}, []string{"filter", "tag"}, endpoint.GetDocumentsByTag)
Add(rt, RoutePrefixPrivate, "documents", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentsByFolder)
Add(rt, RoutePrefixPrivate, "documents/{documentID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocument)
Add(rt, RoutePrefixPrivate, "documents/{documentID}", []string{"PUT", "OPTIONS"}, nil, endpoint.UpdateDocument)
Add(rt, RoutePrefixPrivate, "documents/{documentID}", []string{"DELETE", "OPTIONS"}, nil, endpoint.DeleteDocument)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/activity", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentActivity)
// Document Page
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/level", []string{"POST", "OPTIONS"}, nil, endpoint.ChangeDocumentPageLevel)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/sequence", []string{"POST", "OPTIONS"}, nil, endpoint.ChangeDocumentPageSequence)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/batch", []string{"POST", "OPTIONS"}, nil, endpoint.GetDocumentPagesBatch)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/{pageID}/revisions", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentPageRevisions)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/{pageID}/revisions/{revisionID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentPageDiff)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/{pageID}/revisions/{revisionID}", []string{"POST", "OPTIONS"}, nil, endpoint.RollbackDocumentPage)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/revisions", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentRevisions)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentPages)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/{pageID}", []string{"PUT", "OPTIONS"}, nil, endpoint.UpdateDocumentPage)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/{pageID}", []string{"DELETE", "OPTIONS"}, nil, endpoint.DeleteDocumentPage)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages", []string{"DELETE", "OPTIONS"}, nil, endpoint.DeleteDocumentPages)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/{pageID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentPage)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages", []string{"POST", "OPTIONS"}, nil, endpoint.AddDocumentPage)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/attachments", []string{"GET", "OPTIONS"}, nil, endpoint.GetAttachments)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/attachments/{attachmentID}", []string{"DELETE", "OPTIONS"}, nil, endpoint.DeleteAttachment)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/attachments", []string{"POST", "OPTIONS"}, nil, endpoint.AddAttachments)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/{pageID}/meta", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentPageMeta)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/pages/{pageID}/copy/{targetID}", []string{"POST", "OPTIONS"}, nil, endpoint.CopyPage)
// Organization
Add(rt, RoutePrefixPrivate, "organizations/{orgID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetOrganization)
Add(rt, RoutePrefixPrivate, "organizations/{orgID}", []string{"PUT", "OPTIONS"}, nil, endpoint.UpdateOrganization)
// Folder
Add(rt, RoutePrefixPrivate, "folders/{folderID}", []string{"DELETE", "OPTIONS"}, nil, endpoint.DeleteFolder)
Add(rt, RoutePrefixPrivate, "folders/{folderID}/move/{moveToId}", []string{"DELETE", "OPTIONS"}, nil, endpoint.RemoveFolder)
Add(rt, RoutePrefixPrivate, "folders/{folderID}/permissions", []string{"PUT", "OPTIONS"}, nil, endpoint.SetFolderPermissions)
Add(rt, RoutePrefixPrivate, "folders/{folderID}/permissions", []string{"GET", "OPTIONS"}, nil, endpoint.GetFolderPermissions)
Add(rt, RoutePrefixPrivate, "folders/{folderID}/invitation", []string{"POST", "OPTIONS"}, nil, endpoint.InviteToFolder)
Add(rt, RoutePrefixPrivate, "folders", []string{"GET", "OPTIONS"}, []string{"filter", "viewers"}, endpoint.GetFolderVisibility)
Add(rt, RoutePrefixPrivate, "folders", []string{"POST", "OPTIONS"}, nil, endpoint.AddFolder)
Add(rt, RoutePrefixPrivate, "folders", []string{"GET", "OPTIONS"}, nil, endpoint.GetFolders)
Add(rt, RoutePrefixPrivate, "folders/{folderID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetFolder)
Add(rt, RoutePrefixPrivate, "folders/{folderID}", []string{"PUT", "OPTIONS"}, nil, endpoint.UpdateFolder)
// Users
Add(rt, RoutePrefixPrivate, "users/{userID}/password", []string{"POST", "OPTIONS"}, nil, endpoint.ChangeUserPassword)
Add(rt, RoutePrefixPrivate, "users/{userID}/permissions", []string{"GET", "OPTIONS"}, nil, endpoint.GetUserFolderPermissions)
Add(rt, RoutePrefixPrivate, "users", []string{"POST", "OPTIONS"}, nil, endpoint.AddUser)
Add(rt, RoutePrefixPrivate, "users/folder/{folderID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetFolderUsers)
Add(rt, RoutePrefixPrivate, "users", []string{"GET", "OPTIONS"}, nil, endpoint.GetOrganizationUsers)
Add(rt, RoutePrefixPrivate, "users/{userID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetUser)
Add(rt, RoutePrefixPrivate, "users/{userID}", []string{"PUT", "OPTIONS"}, nil, endpoint.UpdateUser)
Add(rt, RoutePrefixPrivate, "users/{userID}", []string{"DELETE", "OPTIONS"}, nil, endpoint.DeleteUser)
Add(rt, RoutePrefixPrivate, "users/sync", []string{"GET", "OPTIONS"}, nil, endpoint.SyncKeycloak)
// Search
Add(rt, RoutePrefixPrivate, "search", []string{"GET", "OPTIONS"}, nil, endpoint.SearchDocuments)
// Templates
Add(rt, RoutePrefixPrivate, "templates", []string{"POST", "OPTIONS"}, nil, endpoint.SaveAsTemplate)
Add(rt, RoutePrefixPrivate, "templates", []string{"GET", "OPTIONS"}, nil, endpoint.GetSavedTemplates)
Add(rt, RoutePrefixPrivate, "templates/stock", []string{"GET", "OPTIONS"}, nil, endpoint.GetStockTemplates)
Add(rt, RoutePrefixPrivate, "templates/{templateID}/folder/{folderID}", []string{"POST", "OPTIONS"}, []string{"type", "stock"}, endpoint.StartDocumentFromStockTemplate)
Add(rt, RoutePrefixPrivate, "templates/{templateID}/folder/{folderID}", []string{"POST", "OPTIONS"}, []string{"type", "saved"}, endpoint.StartDocumentFromSavedTemplate)
// Sections
Add(rt, RoutePrefixPrivate, "sections", []string{"GET", "OPTIONS"}, nil, endpoint.GetSections)
Add(rt, RoutePrefixPrivate, "sections", []string{"POST", "OPTIONS"}, nil, endpoint.RunSectionCommand)
Add(rt, RoutePrefixPrivate, "sections/refresh", []string{"GET", "OPTIONS"}, nil, endpoint.RefreshSections)
Add(rt, RoutePrefixPrivate, "sections/blocks/space/{folderID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetBlocksForSpace)
Add(rt, RoutePrefixPrivate, "sections/blocks/{blockID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetBlock)
Add(rt, RoutePrefixPrivate, "sections/blocks/{blockID}", []string{"PUT", "OPTIONS"}, nil, endpoint.UpdateBlock)
Add(rt, RoutePrefixPrivate, "sections/blocks/{blockID}", []string{"DELETE", "OPTIONS"}, nil, endpoint.DeleteBlock)
Add(rt, RoutePrefixPrivate, "sections/blocks", []string{"POST", "OPTIONS"}, nil, endpoint.AddBlock)
Add(rt, RoutePrefixPrivate, "sections/targets", []string{"GET", "OPTIONS"}, nil, endpoint.GetPageMoveCopyTargets)
// Links
Add(rt, RoutePrefixPrivate, "links/{folderID}/{documentID}/{pageID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetLinkCandidates)
Add(rt, RoutePrefixPrivate, "links", []string{"GET", "OPTIONS"}, nil, endpoint.SearchLinkCandidates)
Add(rt, RoutePrefixPrivate, "documents/{documentID}/links", []string{"GET", "OPTIONS"}, nil, endpoint.GetDocumentLinks)
// Global installation-wide config
Add(rt, RoutePrefixPrivate, "global/smtp", []string{"GET", "OPTIONS"}, nil, endpoint.GetSMTPConfig)
Add(rt, RoutePrefixPrivate, "global/smtp", []string{"PUT", "OPTIONS"}, nil, endpoint.SaveSMTPConfig)
Add(rt, RoutePrefixPrivate, "global/license", []string{"GET", "OPTIONS"}, nil, endpoint.GetLicense)
Add(rt, RoutePrefixPrivate, "global/license", []string{"PUT", "OPTIONS"}, nil, endpoint.SaveLicense)
Add(rt, RoutePrefixPrivate, "global/auth", []string{"GET", "OPTIONS"}, nil, endpoint.GetAuthConfig)
Add(rt, RoutePrefixPrivate, "global/auth", []string{"PUT", "OPTIONS"}, nil, endpoint.SaveAuthConfig)
// Pinned items
Add(rt, RoutePrefixPrivate, "pin/{userID}", []string{"POST", "OPTIONS"}, nil, endpoint.AddPin)
Add(rt, RoutePrefixPrivate, "pin/{userID}", []string{"GET", "OPTIONS"}, nil, endpoint.GetUserPins)
Add(rt, RoutePrefixPrivate, "pin/{userID}/sequence", []string{"POST", "OPTIONS"}, nil, endpoint.UpdatePinSequence)
Add(rt, RoutePrefixPrivate, "pin/{userID}/{pinID}", []string{"DELETE", "OPTIONS"}, nil, endpoint.DeleteUserPin)
// Single page app handler
Add(rt, RoutePrefixRoot, "robots.txt", []string{"GET", "OPTIONS"}, nil, endpoint.GetRobots)
Add(rt, RoutePrefixRoot, "sitemap.xml", []string{"GET", "OPTIONS"}, nil, endpoint.GetSitemap)
Add(rt, RoutePrefixRoot, "{rest:.*}", nil, nil, web.EmberHandler)
}

133
server/routing/table.go Normal file
View file

@ -0,0 +1,133 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package routing
import (
"encoding/json"
"net/http"
"sort"
"strings"
"github.com/documize/community/core/env"
"github.com/gorilla/mux"
)
const (
// RoutePrefixPublic used for the unsecured api
RoutePrefixPublic = "/api/public/"
// RoutePrefixPrivate used for secured api (requiring api)
RoutePrefixPrivate = "/api/"
// RoutePrefixRoot used for unsecured endpoints at root (e.g. robots.txt)
RoutePrefixRoot = "/"
)
type routeDef struct {
Prefix string
Path string
Methods []string
Queries []string
}
// RouteFunc describes end-point functions
type RouteFunc func(http.ResponseWriter, *http.Request)
type routeMap map[string]RouteFunc
var routes = make(routeMap)
func routesKey(rt env.Runtime, prefix, path string, methods, queries []string) (string, error) {
rd := routeDef{
Prefix: prefix,
Path: path,
Methods: methods,
Queries: queries,
}
b, e := json.Marshal(rd)
if e != nil {
rt.Log.Error("routesKey failed for "+path, e)
}
return string(b), e
}
// Add an endpoint to those that will be processed when Serve() is called.
func Add(rt env.Runtime, prefix, path string, methods, queries []string, endPtFn RouteFunc) error {
k, e := routesKey(rt, prefix, path, methods, queries)
if e != nil {
return e
}
routes[k] = endPtFn
return nil
}
// Remove an endpoint.
func Remove(rt env.Runtime, prefix, path string, methods, queries []string) error {
k, e := routesKey(rt, prefix, path, methods, queries)
if e != nil {
return e
}
delete(routes, k)
return nil
}
type routeSortItem struct {
def routeDef
fun RouteFunc
ord int
}
type routeSorter []routeSortItem
func (s routeSorter) Len() int { return len(s) }
func (s routeSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s routeSorter) Less(i, j int) bool {
if s[i].def.Prefix == s[j].def.Prefix && s[i].def.Path == s[j].def.Path {
return len(s[i].def.Queries) > len(s[j].def.Queries)
}
return s[i].ord < s[j].ord
}
// BuildRoutes returns all matching routes for specified scope.
func BuildRoutes(rt env.Runtime, prefix string) *mux.Router {
var rs routeSorter
for k, v := range routes {
var rd routeDef
if err := json.Unmarshal([]byte(k), &rd); err != nil {
rt.Log.Error("buildRoutes json.Unmarshal", err)
} else {
if rd.Prefix == prefix {
order := strings.Index(rd.Path, "{")
if order == -1 {
order = len(rd.Path)
}
order = -order
rs = append(rs, routeSortItem{def: rd, fun: v, ord: order})
}
}
}
sort.Sort(rs)
router := mux.NewRouter()
for _, it := range rs {
//fmt.Printf("DEBUG buildRoutes: %d %#v\n", it.ord, it.def)
x := router.HandleFunc(it.def.Prefix+it.def.Path, it.fun)
if len(it.def.Methods) > 0 {
y := x.Methods(it.def.Methods...)
if len(it.def.Queries) > 0 {
y.Queries(it.def.Queries...)
}
}
}
return router
}

142
server/server.go Normal file
View file

@ -0,0 +1,142 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package server
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/codegangsta/negroni"
"github.com/documize/community/core/api"
"github.com/documize/community/core/api/endpoint"
"github.com/documize/community/core/api/plugins"
"github.com/documize/community/core/database"
"github.com/documize/community/core/env"
"github.com/documize/community/server/routing"
"github.com/documize/community/server/web"
"github.com/gorilla/mux"
)
var testHost string // used during automated testing
// Start router to handle all HTTP traffic.
func Start(rt env.Runtime, ready chan struct{}) {
routing.RegisterEndpoints(rt)
err := plugins.LibSetup()
if err != nil {
rt.Log.Error("Terminating before running - invalid plugin.json", err)
os.Exit(1)
}
rt.Log.Info(fmt.Sprintf("Starting %s version %s", api.Runtime.Product.Title, api.Runtime.Product.Version))
switch api.Runtime.Flags.SiteMode {
case web.SiteModeOffline:
rt.Log.Info("Serving OFFLINE web server")
case web.SiteModeSetup:
routing.Add(rt, routing.RoutePrefixPrivate, "setup", []string{"POST", "OPTIONS"}, nil, database.Create)
rt.Log.Info("Serving SETUP web server")
case web.SiteModeBadDB:
rt.Log.Info("Serving BAD DATABASE web server")
default:
rt.Log.Info("Starting web server")
}
router := mux.NewRouter()
// "/api/public/..."
router.PathPrefix(routing.RoutePrefixPublic).Handler(negroni.New(
negroni.HandlerFunc(cors),
negroni.Wrap(routing.BuildRoutes(rt, routing.RoutePrefixPublic)),
))
// "/api/..."
router.PathPrefix(routing.RoutePrefixPrivate).Handler(negroni.New(
negroni.HandlerFunc(endpoint.Authorize),
negroni.Wrap(routing.BuildRoutes(rt, routing.RoutePrefixPrivate)),
))
// "/..."
router.PathPrefix(routing.RoutePrefixRoot).Handler(negroni.New(
negroni.HandlerFunc(cors),
negroni.Wrap(routing.BuildRoutes(rt, routing.RoutePrefixRoot)),
))
n := negroni.New()
n.Use(negroni.NewStatic(web.StaticAssetsFileSystem()))
n.Use(negroni.HandlerFunc(cors))
n.Use(negroni.HandlerFunc(metrics))
n.UseHandler(router)
if !api.Runtime.Flags.SSLEnabled() {
rt.Log.Info("Starting non-SSL server on " + api.Runtime.Flags.HTTPPort)
n.Run(testHost + ":" + api.Runtime.Flags.HTTPPort)
} else {
if api.Runtime.Flags.ForceHTTPPort2SSL != "" {
rt.Log.Info("Starting non-SSL server on " + api.Runtime.Flags.ForceHTTPPort2SSL + " and redirecting to SSL server on " + api.Runtime.Flags.HTTPPort)
go func() {
err := http.ListenAndServe(":"+api.Runtime.Flags.ForceHTTPPort2SSL, http.HandlerFunc(
func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Connection", "close")
var host = strings.Replace(req.Host, api.Runtime.Flags.ForceHTTPPort2SSL, api.Runtime.Flags.HTTPPort, 1) + req.RequestURI
http.Redirect(w, req, "https://"+host, http.StatusMovedPermanently)
}))
if err != nil {
rt.Log.Error("ListenAndServe on "+api.Runtime.Flags.ForceHTTPPort2SSL, err)
}
}()
}
rt.Log.Info("Starting SSL server on " + api.Runtime.Flags.HTTPPort + " with " + api.Runtime.Flags.SSLCertFile + " " + api.Runtime.Flags.SSLKeyFile)
// TODO: https://blog.gopheracademy.com/advent-2016/exposing-go-on-the-internet/
server := &http.Server{Addr: ":" + api.Runtime.Flags.HTTPPort, Handler: n /*, TLSConfig: myTLSConfig*/}
server.SetKeepAlivesEnabled(true)
if err := server.ListenAndServeTLS(api.Runtime.Flags.SSLCertFile, api.Runtime.Flags.SSLKeyFile); err != nil {
rt.Log.Error("ListenAndServeTLS on "+api.Runtime.Flags.HTTPPort, err)
}
}
}
func cors(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS, PATCH")
w.Header().Set("Access-Control-Allow-Headers", "host, content-type, accept, authorization, origin, referer, user-agent, cache-control, x-requested-with")
w.Header().Set("Access-Control-Expose-Headers", "x-documize-version, x-documize-status")
if r.Method == "OPTIONS" {
w.Header().Add("X-Documize-Version", api.Runtime.Product.Version)
w.Header().Add("Cache-Control", "no-cache")
w.Write([]byte(""))
return
}
next(w, r)
}
func metrics(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w.Header().Add("X-Documize-Version", api.Runtime.Product.Version)
w.Header().Add("Cache-Control", "no-cache")
// Prevent page from being displayed in an iframe
w.Header().Add("X-Frame-Options", "DENY")
next(w, r)
}

48
server/web/embed.go Normal file
View file

@ -0,0 +1,48 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
// Package web contains the Documize static web data.
package web
import (
"net/http"
)
// EmbedHandler is defined in each embed directory
type EmbedHandler interface {
Asset(string) ([]byte, error)
AssetDir(string) ([]string, error)
StaticAssetsFileSystem() http.FileSystem
}
// Embed allows access to the embedded data
var Embed EmbedHandler
// StaticAssetsFileSystem data encoded in the go:generate above.
func StaticAssetsFileSystem() http.FileSystem {
return Embed.StaticAssetsFileSystem()
//return &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "bindata/public"}
}
// ReadFile is intended to substitute for ioutil.ReadFile().
func ReadFile(filename string) ([]byte, error) {
return Embed.Asset("bindata/" + filename)
}
// Asset fetch.
func Asset(location string) ([]byte, error) {
return Embed.Asset(location)
}
// AssetDir returns web app "assets" folder.
func AssetDir(dir string) ([]string, error) {
return Embed.AssetDir(dir)
}

68
server/web/serve.go Normal file
View file

@ -0,0 +1,68 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
// Package web contains the Documize static web data.
package web
import (
"html/template"
"net/http"
"github.com/documize/community/core/api"
"github.com/documize/community/core/secrets"
)
const (
// SiteModeNormal serves app
SiteModeNormal = ""
// SiteModeOffline serves offline.html
SiteModeOffline = "1"
// SiteModeSetup tells Ember to serve setup route
SiteModeSetup = "2"
// SiteModeBadDB redirects to db-error.html page
SiteModeBadDB = "3"
)
// SiteInfo describes set-up information about the site
var SiteInfo struct {
DBname, DBhash, Issue string
}
func init() {
SiteInfo.DBhash = secrets.GenerateRandomPassword() // do this only once
}
// EmberHandler serves HTML web pages
func EmberHandler(w http.ResponseWriter, r *http.Request) {
filename := "index.html"
switch api.Runtime.Flags.SiteMode {
case SiteModeOffline:
filename = "offline.html"
case SiteModeSetup:
// NoOp
case SiteModeBadDB:
filename = "db-error.html"
default:
SiteInfo.DBhash = ""
}
data, err := Embed.Asset("bindata/" + filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
emberView := template.Must(template.New(filename).Parse(string(data)))
if err := emberView.Execute(w, SiteInfo); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}