Skip to content

Commit

Permalink
v1.2.0: Go Fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashley Primo committed Jan 17, 2022
1 parent c9253b6 commit 63681e1
Show file tree
Hide file tree
Showing 7 changed files with 111 additions and 115 deletions.
5 changes: 2 additions & 3 deletions documentation/documentation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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))))
}

40 changes: 20 additions & 20 deletions initialize/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
8 changes: 3 additions & 5 deletions initialize/global.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
)

24 changes: 12 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)

Expand Down
43 changes: 21 additions & 22 deletions metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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())
}
}
}
84 changes: 42 additions & 42 deletions qr/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) {
Expand All @@ -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
Expand All @@ -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
Expand Down
Loading

0 comments on commit 63681e1

Please sign in to comment.