From d473e7819e0071ed5ab7bf9f892eb858b1cfbe75 Mon Sep 17 00:00:00 2001 From: michael1011 Date: Thu, 29 Mar 2018 13:44:08 +0200 Subject: [PATCH] added option add Access-Control-Allow-Origin header --- config.go | 9 ++++++--- lightningtip.go | 18 ++++++++++++++---- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/config.go b/config.go index 9638a60..2d93c8c 100644 --- a/config.go +++ b/config.go @@ -16,7 +16,8 @@ const ( defaultLogFile = "lightningTip.log" defaultLogLevel = "debug" - defaultRESTHost = "localhost:8081" + defaultRESTHost = "localhost:8081" + defaultAccessDomain = "" defaultTipExpiry = 3600 @@ -31,7 +32,8 @@ type config struct { LogFile string `long:"logfile" Description:"Log file location"` LogLevel string `long:"loglevel" Description:"Log level: debug, info, warning, error"` - RESTHost string `long:"resthost" Description:"Host for the rest interface of LightningTip"` + RESTHost string `long:"resthost" Description:"Host for the rest interface of LightningTip"` + AccessDomain string `long:"accessdomain" Description:"The domain you are using LightningTip from"` TipExpiry int64 `long:"tipexpiry" Description:"Invoice expiry time in seconds"` @@ -51,7 +53,8 @@ func initConfig() { LogFile: defaultLogFile, LogLevel: defaultLogLevel, - RESTHost: defaultRESTHost, + RESTHost: defaultRESTHost, + AccessDomain: defaultAccessDomain, TipExpiry: defaultTipExpiry, diff --git a/lightningtip.go b/lightningtip.go index 3bbc3f7..6227414 100644 --- a/lightningtip.go +++ b/lightningtip.go @@ -68,12 +68,12 @@ func main() { eventSrv = eventsource.NewServer() - http.HandleFunc("/", notFoundHandler) - http.HandleFunc("/getinvoice", getInvoiceHandler) - http.HandleFunc("/eventsource", eventSrv.Handler(eventChannel)) + http.Handle("/", handleHeaders(notFoundHandler)) + http.Handle("/getinvoice", handleHeaders(getInvoiceHandler)) + http.Handle("/eventsource", handleHeaders(eventSrv.Handler(eventChannel))) // Alternative for browsers which don't support EventSource (Internet Explorer and Edge) - http.HandleFunc("/invoicesettled", invoiceSettledHandler) + http.Handle("/invoicesettled", handleHeaders(invoiceSettledHandler)) log.Debug("Starting ticker to clear expired invoices") @@ -255,6 +255,16 @@ func notFoundHandler(writer http.ResponseWriter, request *http.Request) { writeError(writer, "Not found") } +func handleHeaders(handler func(w http.ResponseWriter, r *http.Request)) http.Handler { + return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if cfg.AccessDomain != "" { + writer.Header().Add("Access-Control-Allow-Origin", cfg.AccessDomain) + } + + handler(writer, request) + }) +} + func writeError(writer http.ResponseWriter, message string) { writer.WriteHeader(http.StatusBadRequest)