From 27f3ac785dc4278e736b0ea5b220aa9d259d8152 Mon Sep 17 00:00:00 2001 From: Ashley Primo Date: Mon, 17 Jan 2022 08:57:45 +0000 Subject: [PATCH 1/4] v1.2.0: Allow Metrics to be served on independent socket + change address to host --- initialize/flags.go | 32 ++++++++++++++++++-------------- initialize/global.go | 2 +- main.go | 15 ++++----------- metrics.go | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 26 deletions(-) diff --git a/initialize/flags.go b/initialize/flags.go index 36d5078..fa8511a 100644 --- a/initialize/flags.go +++ b/initialize/flags.go @@ -8,31 +8,35 @@ import ( var ( // Webserver Flags - PortNumber = flag.String("port", "8080", "The port number to listen on for HTTP requests.") - Address = flag.String("address", "0.0.0.0", "The address to listen on for HTTP requests.") + PortNumber = flag.String("port", "8080", "The port number to listen on for HTTP requests.") + Host = flag.String("host", "0.0.0.0", "The host/address to listen on for HTTP requests.") - Https = flag.Bool("https", false, "Enable, or Disable HTTPS") - Server_crt = flag.String("server_crt", "server.crt", "Certificate file") - Server_key = flag.String("server_key", "server.key", "Certificate key file.") + Https = flag.Bool("https", false, "Enable, or Disable HTTPS") + Server_crt = flag.String("server_crt", "server.crt", "Certificate file") + Server_key = flag.String("server_key", "server.key", "Certificate key file.") // QR Setup Flags - QREndpoint = flag.String("qr.endpoint", "/", "QR API endpoint location") + QREndpoint = flag.String("qr.endpoint", "/", "QR API endpoint location") - DefaultSize = flag.Int("qr.default.size", 250, "Default QR Image Size, if unspecified by end user.") - MaxSize = flag.Int("qr.max.size", 1000, "Maximum QR Image Size") + DefaultSize = flag.Int("qr.default.size", 250, "Default QR Image Size, if unspecified by end user.") + MaxSize = flag.Int("qr.max.size", 1000, "Maximum QR Image Size") // Logging Flags - LogLevel = flag.String("log.level", "info", "The level of logs to log") - LogConn = flag.Bool("log.conn", true, "Log connections to API") + LogLevel = flag.String("log.level", "info", "The level of logs to log") + LogConn = flag.Bool("log.conn", true, "Log connections to API") // Documentation Flags - EnableDocs = flag.Bool("enable.docs", true, "Enable documentation (/docs) endpoint.") + EnableDocs = flag.Bool("enable.docs", true, "Enable documentation (/docs) endpoint.") - // Metrics Flagd - EnableMetrics = flag.Bool("enable.metrics", true, "Enable metrics (/metrics) endpoint.") + // Metrics Flags + EnableMetrics = flag.Bool("enable.metrics", true, "Enable metrics (/metrics) endpoint.") + + MetricServer = flag.Bool("enable.metrics.server", false, "Enable seperate metrics server") + MetricServerPort = flag.String("metrics.server.port", "9100", "The port number to listen on for metrics HTTP requests.") + MetricServerHost = flag.String("metrics.server.host", "0.0.0.0", "The host/address to listen on for metrics HTTP requests.") // Misc Flags - VersionFlag = flag.Bool("v", false, "Outputs package version") + VersionFlag = flag.Bool("v", false, "Outputs package version") ) func Flags() { diff --git a/initialize/global.go b/initialize/global.go index 510681a..ebe889d 100644 --- a/initialize/global.go +++ b/initialize/global.go @@ -5,7 +5,7 @@ import ( ) const ( - Version string = "1.1.0" + Version string = "1.2.0" MetricNamespace string = "qr_generator" ) diff --git a/main.go b/main.go index f440f0b..d2b3812 100644 --- a/main.go +++ b/main.go @@ -10,8 +10,6 @@ import ( "github.com/ashleyprimo/go-qr-generator/initialize" "github.com/ashleyprimo/go-qr-generator/qr" "github.com/ashleyprimo/go-qr-generator/documentation" - - "github.com/prometheus/client_golang/prometheus/promhttp" ) func loglevel(opt string) { @@ -43,6 +41,7 @@ func main() { } loglevel(*initialize.LogLevel) + metrics() // QR Engine API Endpoint http.HandleFunc(*initialize.QREndpoint, qr.Engine) @@ -56,17 +55,11 @@ func main() { // Health Check Endpoint http.HandleFunc("/health", health) - // Metrics Endpoint - if *initialize.EnableMetrics { - log.Debugf("Metrics Endpoint Enabled") - http.Handle("/metrics", promhttp.Handler()) - } - - log.Infof("Listening for requests on %s:%s", *initialize.Address, *initialize.PortNumber) + log.Infof("Listening for requests on %s:%s", *initialize.Host, *initialize.PortNumber) if *initialize.Https { - log.Fatalf("Failed to start web server with TLS: %s", http.ListenAndServeTLS(fmt.Sprintf("%s:%s", *initialize.Address, *initialize.PortNumber), *initialize.Server_crt, *initialize.Server_key, nil)) + log.Fatalf("Failed to start web server with TLS: %s", http.ListenAndServeTLS(fmt.Sprintf("%s:%s", *initialize.Host, *initialize.PortNumber), *initialize.Server_crt, *initialize.Server_key, nil)) } else { - log.Fatalf("Failed to start web server: %s", http.ListenAndServe(fmt.Sprintf("%s:%s", *initialize.Address, *initialize.PortNumber), nil)) + log.Fatalf("Failed to start web server: %s", http.ListenAndServe(fmt.Sprintf("%s:%s", *initialize.Host, *initialize.PortNumber), nil)) } } diff --git a/metrics.go b/metrics.go index 6c7289a..6cbdd80 100644 --- a/metrics.go +++ b/metrics.go @@ -1,8 +1,15 @@ package main import ( + "fmt" + "time" + "net/http" + + log "github.com/sirupsen/logrus" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/ashleyprimo/go-qr-generator/initialize" ) @@ -20,3 +27,29 @@ var ( ) ) + +func metrics() { + // Metrics Endpoint + if *initialize.EnableMetrics { + log.Debugf("Metrics Endpoint Enabled") + if *initialize.MetricServer { + log.Debugf("Metrics Server Enabled") + log.Infof("Listening for metrics requests on %s:%s", *initialize.MetricServerHost, *initialize.MetricServerPort) + go func() { + mux := http.NewServeMux() + mux.Handle("/metrics", promhttp.Handler()) + srv := &http.Server{ + Addr: fmt.Sprintf("%s:%s", *initialize.MetricServerHost, *initialize.MetricServerPort), + Handler: mux, + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 3 * time.Minute, + } + log.Fatalf("Failed to start web server: %s", srv.ListenAndServe()) + }() + + } else { + http.Handle("/metrics", promhttp.Handler()) + } + } +} From c1bf2b7a48ec8b2a49175b3ef01cfeb00956cabc Mon Sep 17 00:00:00 2001 From: Ashley Primo Date: Mon, 17 Jan 2022 09:00:44 +0000 Subject: [PATCH 2/4] v1.2.0: Fix Readme --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 19d3b75..6f30b87 100644 --- a/README.md +++ b/README.md @@ -11,18 +11,24 @@ ``` Usage of ./go-qr-generator: - -address string - The address to listen on for HTTP requests. (default "0.0.0.0") -enable.docs Enable documentation (/docs) endpoint. (default true) -enable.metrics Enable metrics (/metrics) endpoint. (default true) + -enable.metrics.server + Enable seperate metrics server + -host string + The host/address to listen on for HTTP requests. (default "0.0.0.0") -https Enable, or Disable HTTPS -log.conn Log connections to API (default true) -log.level string The level of logs to log (default "info") + -metrics.server.host string + The host/address to listen on for metrics HTTP requests. (default "0.0.0.0") + -metrics.server.port string + The port number to listen on for metrics HTTP requests. (default "9100") -port string The port number to listen on for HTTP requests. (default "8080") -qr.default.size int From c9253b661ef0d606d494733ec876ff5995213dcf Mon Sep 17 00:00:00 2001 From: Ashley Primo Date: Mon, 17 Jan 2022 09:03:35 +0000 Subject: [PATCH 3/4] v1.2.0: Go Mod Tidy --- go.mod | 2 +- go.sum | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 489201a..b779aa9 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.17 require ( github.com/boombuler/barcode v1.0.1 + github.com/prometheus/client_golang v1.11.0 github.com/sirupsen/logrus v1.8.1 ) @@ -12,7 +13,6 @@ require ( github.com/cespare/xxhash/v2 v2.1.1 // indirect github.com/golang/protobuf v1.4.3 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect - github.com/prometheus/client_golang v1.11.0 // indirect github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.26.0 // indirect github.com/prometheus/procfs v0.6.0 // indirect diff --git a/go.sum b/go.sum index 7adc7a9..2bfe4c9 100644 --- a/go.sum +++ b/go.sum @@ -38,6 +38,7 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= @@ -90,9 +91,9 @@ github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -113,7 +114,6 @@ golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -125,6 +125,7 @@ golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= @@ -142,4 +143,5 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= From 63681e14a4fd439f78383e833c3d698c87996b66 Mon Sep 17 00:00:00 2001 From: Ashley Primo Date: Mon, 17 Jan 2022 09:05:22 +0000 Subject: [PATCH 4/4] v1.2.0: Go Fmt --- documentation/documentation.go | 5 +- initialize/flags.go | 40 ++++++++-------- initialize/global.go | 8 ++-- main.go | 24 +++++----- metrics.go | 43 +++++++++-------- qr/engine.go | 84 +++++++++++++++++----------------- qr/metrics.go | 22 ++++----- 7 files changed, 111 insertions(+), 115 deletions(-) diff --git a/documentation/documentation.go b/documentation/documentation.go index 23f4baf..c50a952 100644 --- a/documentation/documentation.go +++ b/documentation/documentation.go @@ -2,10 +2,10 @@ package docs import ( "fmt" + "net/http" "strconv" - "net/http" - "github.com/ashleyprimo/go-qr-generator/initialize" + "github.com/ashleyprimo/go-qr-generator/initialize" ) func Landing(w http.ResponseWriter, r *http.Request) { @@ -54,4 +54,3 @@ func Landing(w http.ResponseWriter, r *http.Request) { ) w.Write([]byte(fmt.Sprintf(documentationPage, initialize.ApplicationName, r.Host, *initialize.QREndpoint, strconv.Itoa(*initialize.MaxSize), strconv.Itoa(*initialize.DefaultSize)))) } - diff --git a/initialize/flags.go b/initialize/flags.go index fa8511a..14d2144 100644 --- a/initialize/flags.go +++ b/initialize/flags.go @@ -3,40 +3,40 @@ package initialize import ( "flag" - log "github.com/sirupsen/logrus" + log "github.com/sirupsen/logrus" ) var ( - // Webserver Flags - PortNumber = flag.String("port", "8080", "The port number to listen on for HTTP requests.") - Host = flag.String("host", "0.0.0.0", "The host/address to listen on for HTTP requests.") + // Webserver Flags + PortNumber = flag.String("port", "8080", "The port number to listen on for HTTP requests.") + Host = flag.String("host", "0.0.0.0", "The host/address to listen on for HTTP requests.") - Https = flag.Bool("https", false, "Enable, or Disable HTTPS") - Server_crt = flag.String("server_crt", "server.crt", "Certificate file") - Server_key = flag.String("server_key", "server.key", "Certificate key file.") + Https = flag.Bool("https", false, "Enable, or Disable HTTPS") + Server_crt = flag.String("server_crt", "server.crt", "Certificate file") + Server_key = flag.String("server_key", "server.key", "Certificate key file.") - // QR Setup Flags - QREndpoint = flag.String("qr.endpoint", "/", "QR API endpoint location") + // QR Setup Flags + QREndpoint = flag.String("qr.endpoint", "/", "QR API endpoint location") - DefaultSize = flag.Int("qr.default.size", 250, "Default QR Image Size, if unspecified by end user.") - MaxSize = flag.Int("qr.max.size", 1000, "Maximum QR Image Size") + DefaultSize = flag.Int("qr.default.size", 250, "Default QR Image Size, if unspecified by end user.") + MaxSize = flag.Int("qr.max.size", 1000, "Maximum QR Image Size") - // Logging Flags - LogLevel = flag.String("log.level", "info", "The level of logs to log") - LogConn = flag.Bool("log.conn", true, "Log connections to API") + // Logging Flags + LogLevel = flag.String("log.level", "info", "The level of logs to log") + LogConn = flag.Bool("log.conn", true, "Log connections to API") - // Documentation Flags - EnableDocs = flag.Bool("enable.docs", true, "Enable documentation (/docs) endpoint.") + // Documentation Flags + EnableDocs = flag.Bool("enable.docs", true, "Enable documentation (/docs) endpoint.") // Metrics Flags - EnableMetrics = flag.Bool("enable.metrics", true, "Enable metrics (/metrics) endpoint.") + EnableMetrics = flag.Bool("enable.metrics", true, "Enable metrics (/metrics) endpoint.") MetricServer = flag.Bool("enable.metrics.server", false, "Enable seperate metrics server") MetricServerPort = flag.String("metrics.server.port", "9100", "The port number to listen on for metrics HTTP requests.") - MetricServerHost = flag.String("metrics.server.host", "0.0.0.0", "The host/address to listen on for metrics HTTP requests.") + MetricServerHost = flag.String("metrics.server.host", "0.0.0.0", "The host/address to listen on for metrics HTTP requests.") - // Misc Flags - VersionFlag = flag.Bool("v", false, "Outputs package version") + // Misc Flags + VersionFlag = flag.Bool("v", false, "Outputs package version") ) func Flags() { diff --git a/initialize/global.go b/initialize/global.go index ebe889d..7b076a2 100644 --- a/initialize/global.go +++ b/initialize/global.go @@ -5,12 +5,10 @@ import ( ) const ( - Version string = "1.2.0" - MetricNamespace string = "qr_generator" + Version string = "1.2.0" + MetricNamespace string = "qr_generator" ) var ( - ApplicationName string = os.Args[0] - + ApplicationName string = os.Args[0] ) - diff --git a/main.go b/main.go index d2b3812..e6cfdff 100644 --- a/main.go +++ b/main.go @@ -7,9 +7,9 @@ import ( log "github.com/sirupsen/logrus" - "github.com/ashleyprimo/go-qr-generator/initialize" + "github.com/ashleyprimo/go-qr-generator/documentation" + "github.com/ashleyprimo/go-qr-generator/initialize" "github.com/ashleyprimo/go-qr-generator/qr" - "github.com/ashleyprimo/go-qr-generator/documentation" ) func loglevel(opt string) { @@ -28,32 +28,32 @@ func loglevel(opt string) { } func health(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Write([]byte("Ping.")) + w.WriteHeader(http.StatusOK) + w.Write([]byte("Ping.")) } func main() { - initialize.Flags() + initialize.Flags() if *initialize.VersionFlag { - fmt.Printf("%s v%s", initialize.ApplicationName, initialize.Version) - os.Exit(0) - } + fmt.Printf("%s v%s", initialize.ApplicationName, initialize.Version) + os.Exit(0) + } loglevel(*initialize.LogLevel) - metrics() + metrics() // QR Engine API Endpoint http.HandleFunc(*initialize.QREndpoint, qr.Engine) // Documentation Endpoint if *initialize.EnableDocs { - log.Debugf("Documentation Endpoint Enabled") - http.HandleFunc("/docs", docs.Landing) + log.Debugf("Documentation Endpoint Enabled") + http.HandleFunc("/docs", docs.Landing) } // Health Check Endpoint - http.HandleFunc("/health", health) + http.HandleFunc("/health", health) log.Infof("Listening for requests on %s:%s", *initialize.Host, *initialize.PortNumber) diff --git a/metrics.go b/metrics.go index 6cbdd80..57a50e0 100644 --- a/metrics.go +++ b/metrics.go @@ -2,39 +2,38 @@ package main import ( "fmt" - "time" "net/http" + "time" - log "github.com/sirupsen/logrus" + log "github.com/sirupsen/logrus" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/ashleyprimo/go-qr-generator/initialize" + "github.com/ashleyprimo/go-qr-generator/initialize" ) var ( - versionExport = promauto.NewGauge( - prometheus.GaugeOpts{ - Namespace: initialize.MetricNamespace, - Name: "version", - Help: "current running version", + versionExport = promauto.NewGauge( + prometheus.GaugeOpts{ + Namespace: initialize.MetricNamespace, + Name: "version", + Help: "current running version", ConstLabels: map[string]string{ "version": initialize.Version, }, - }, - ) + }, + ) ) - func metrics() { - // Metrics Endpoint - if *initialize.EnableMetrics { - log.Debugf("Metrics Endpoint Enabled") - if *initialize.MetricServer { - log.Debugf("Metrics Server Enabled") - log.Infof("Listening for metrics requests on %s:%s", *initialize.MetricServerHost, *initialize.MetricServerPort) + // Metrics Endpoint + if *initialize.EnableMetrics { + log.Debugf("Metrics Endpoint Enabled") + if *initialize.MetricServer { + log.Debugf("Metrics Server Enabled") + log.Infof("Listening for metrics requests on %s:%s", *initialize.MetricServerHost, *initialize.MetricServerPort) go func() { mux := http.NewServeMux() mux.Handle("/metrics", promhttp.Handler()) @@ -48,8 +47,8 @@ func metrics() { log.Fatalf("Failed to start web server: %s", srv.ListenAndServe()) }() - } else { - http.Handle("/metrics", promhttp.Handler()) - } - } + } else { + http.Handle("/metrics", promhttp.Handler()) + } + } } diff --git a/qr/engine.go b/qr/engine.go index e7bdf52..6e82b02 100644 --- a/qr/engine.go +++ b/qr/engine.go @@ -3,18 +3,18 @@ package qr import ( "fmt" "net" -// "flag" + // "flag" "bytes" "image/png" + "net/http" "net/url" "strconv" - "net/http" - "github.com/ashleyprimo/go-qr-generator/initialize" + "github.com/ashleyprimo/go-qr-generator/initialize" - log "github.com/sirupsen/logrus" "github.com/boombuler/barcode" "github.com/boombuler/barcode/qr" + log "github.com/sirupsen/logrus" ) func InternalServerError(w http.ResponseWriter, r *http.Request, l string) { @@ -29,26 +29,26 @@ func InternalServerError(w http.ResponseWriter, r *http.Request, l string) { } func BadReqeustError(w http.ResponseWriter, r *http.Request, l string) { - requests.WithLabelValues("4xx").Inc() + requests.WithLabelValues("4xx").Inc() // This is a user error/failure, log as debug. log.Debugf(l) - + // Write Output - w.WriteHeader(http.StatusBadRequest) + w.WriteHeader(http.StatusBadRequest) - w.Header().Set("Content-Type", "text/html") + w.Header().Set("Content-Type", "text/html") w.Write([]byte("Bad Request!")) if *initialize.EnableDocs { w.Write([]byte(fmt.Sprintf(" Maybe try looking at our documentation at %[1]s/docs", r.Host))) } } -func logConnection (r *http.Request) { +func logConnection(r *http.Request) { if *initialize.LogConn { - source, _, _ := net.SplitHostPort(r.RemoteAddr) - log.Infof("Request for %s from %s", r.RequestURI, source) - } + source, _, _ := net.SplitHostPort(r.RemoteAddr) + log.Infof("Request for %s from %s", r.RequestURI, source) + } } func Engine(w http.ResponseWriter, r *http.Request) { @@ -70,21 +70,21 @@ func Engine(w http.ResponseWriter, r *http.Request) { // sizeString (size of QR code) var sizeString string - if _, present := parameters["size"]; present == false { + if _, present := parameters["size"]; present == false { defaultSize := strconv.Itoa(*initialize.DefaultSize) - log.Debugf("No 'size' string provided; will default to %s", defaultSize) + log.Debugf("No 'size' string provided; will default to %s", defaultSize) sizeString = defaultSize - } else { + } else { sizeString = parameters["size"][0] } - log.Debugf("Size String: %s", sizeString) + log.Debugf("Size String: %s", sizeString) // Convert sizeString to sizeInt sizeInt, err := strconv.Atoi(sizeString) if err != nil { - InternalServerError(w, r, "Unable to convert sizeString to sizeInt") - return + InternalServerError(w, r, "Unable to convert sizeString to sizeInt") + return } // Ensure requested size is within set limits @@ -96,56 +96,56 @@ func Engine(w http.ResponseWriter, r *http.Request) { //Unescape Data Input dataStringUnescaped, err := url.QueryUnescape(dataString) if err != nil { - InternalServerError(w, r, "Unable to 'Unescape' data string provided...") - return + InternalServerError(w, r, "Unable to 'Unescape' data string provided...") + return } else { - log.Debugf("Data String Unescaped: %s", dataStringUnescaped,) + log.Debugf("Data String Unescaped: %s", dataStringUnescaped) } // Generate QR code, err := qr.Encode(dataStringUnescaped, qr.L, qr.Auto) - if err != nil { - InternalServerError(w, r, "Failed to generate QR code") - return - } else { - log.Debugf("Generated QR Code: %s", code,) - } + if err != nil { + InternalServerError(w, r, "Failed to generate QR code") + return + } else { + log.Debugf("Generated QR Code: %s", code) + } // Ensure QR scale is possible codeBounds := code.Bounds() codeHeight := codeBounds.Max.Y - codeBounds.Min.Y if sizeInt < codeHeight { - BadReqeustError(w, r, "Requested image size is smaller than actual QR minimum size") + BadReqeustError(w, r, "Requested image size is smaller than actual QR minimum size") return } // Scale the barcode to the appropriate size code, err = barcode.Scale(code, sizeInt, sizeInt) - if err != nil { - InternalServerError(w, r, "Unable to scale QR code.") - return - } else { - log.Debugf("Generated QR Code: %s", code,) - } + if err != nil { + InternalServerError(w, r, "Unable to scale QR code.") + return + } else { + log.Debugf("Generated QR Code: %s", code) + } // Encode PNG buffer := new(bytes.Buffer) if err := png.Encode(buffer, code); err != nil { - InternalServerError(w, r, "Unable to encode PNG from code buffer.") - return + InternalServerError(w, r, "Unable to encode PNG from code buffer.") + return } // Output QR w.Header().Set("Content-Type", "image/png") w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes()))) - if _, err := w.Write(buffer.Bytes()); err != nil { - InternalServerError(w, r, "Unable to write/output QR code.") - return - } else { + if _, err := w.Write(buffer.Bytes()); err != nil { + InternalServerError(w, r, "Unable to write/output QR code.") + return + } else { // Log Success - requests.WithLabelValues("2xx").Inc() - log.Debugf("Successfully wrote QR code") + requests.WithLabelValues("2xx").Inc() + log.Debugf("Successfully wrote QR code") } return diff --git a/qr/metrics.go b/qr/metrics.go index 9c4827c..acfa7ba 100644 --- a/qr/metrics.go +++ b/qr/metrics.go @@ -4,24 +4,24 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "github.com/ashleyprimo/go-qr-generator/initialize" + "github.com/ashleyprimo/go-qr-generator/initialize" ) var ( - numRequests = promauto.NewCounter( - prometheus.CounterOpts{ - Namespace: initialize.MetricNamespace, - Name: "requests_total", - Help: "Total number of requests to QR API endpoint.", - }, - ) + numRequests = promauto.NewCounter( + prometheus.CounterOpts{ + Namespace: initialize.MetricNamespace, + Name: "requests_total", + Help: "Total number of requests to QR API endpoint.", + }, + ) requests = promauto.NewCounterVec( prometheus.CounterOpts{ Namespace: initialize.MetricNamespace, - Name: "requests", - Help: "Completed requests to QR API endpoint.", + Name: "requests", + Help: "Completed requests to QR API endpoint.", }, - []string{"type"}, + []string{"type"}, ) )