Skip to content

Commit

Permalink
[Test] coverage code by tests (#9)
Browse files Browse the repository at this point in the history
[Test] coverage code by tests
  • Loading branch information
JanGalek authored Dec 17, 2024
1 parent f23925d commit f12e527
Show file tree
Hide file tree
Showing 12 changed files with 391 additions and 107 deletions.
25 changes: 21 additions & 4 deletions diago.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,35 @@
package diago

import "github.com/gin-gonic/gin"

type Extension interface {
GetPanelHtml(c *gin.Context) string
GetHtml(c *gin.Context) string
GetJSHtml(c *gin.Context) string
BeforeNext(c *gin.Context)
AfterNext(c *gin.Context)
}

type Diago struct {
Extensions []DiagoExtension
Extensions []Extension

TemplateProvider TemplateProvider
PanelGenerator PanelGenerator
}

func NewDiago() *Diago {
return &Diago{}

return &Diago{
TemplateProvider: NewDefaultTemplateProvider(),
PanelGenerator: NewDefaultPanelGenerator(),
}
}

func (d *Diago) GetExtensions() []DiagoExtension {
func (d *Diago) GetExtensions() []Extension {
return d.Extensions
}

func (d *Diago) AddExtension(extension DiagoExtension) *Diago {
func (d *Diago) AddExtension(extension Extension) *Diago {
d.Extensions = append(d.Extensions, extension)
return d
}
11 changes: 0 additions & 11 deletions diagoExtension.go

This file was deleted.

55 changes: 23 additions & 32 deletions diagoMiddleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package diago
import (
"bytes"
_ "embed"
"fmt"
"github.com/gin-gonic/gin"
"github.com/gouef/router"
"html/template"
"log"
"strings"
"net/http"
)

type DiagoData struct {
Expand All @@ -18,7 +19,7 @@ type DiagoData struct {

func DiagoMiddleware(r *router.Router, d *Diago) gin.HandlerFunc {
return func(c *gin.Context) {

originalWriter := c.Writer
for _, e := range d.GetExtensions() {
e.BeforeNext(c)
}
Expand All @@ -27,10 +28,13 @@ func DiagoMiddleware(r *router.Router, d *Diago) gin.HandlerFunc {
writer := &responseWriter{
ResponseWriter: c.Writer,
buffer: responseBuffer,
statusCode: http.StatusOK,
}

c.Next()
c.Writer = writer

c.Next()
c.Copy()
for _, e := range d.GetExtensions() {
e.AfterNext(c)
}
Expand All @@ -54,59 +58,46 @@ func DiagoMiddleware(r *router.Router, d *Diago) gin.HandlerFunc {
ExtensionsJSHtml: extensionsJSHtml,
}

diagoPanelHTML, err := GenerateDiagoPanelHTML(diagoData)
diagoPanelHTML, err := d.PanelGenerator.GenerateHTML("diagoPanel", d.TemplateProvider, diagoData)

if err != nil {
log.Println("Error generating Diago panel HTML:", err)
return
err = c.Error(err)
c.Status(500)
c.Writer.WriteHeaderNow()
diagoPanelHTML = "Error generating Diago panel HTML"
}

writer.buffer.WriteString(diagoPanelHTML)
}

c.Writer = originalWriter
_, err := c.Writer.Write(responseBuffer.Bytes())
if err != nil {
log.Println("Error writing response:", err)
err = c.Error(err)
c.Status(500)
writer.buffer.WriteString("Error generating Diago panel HTML")
}

// Logování status kódu
status := c.Writer.Status()
log.Printf("Status: %d", status)
}
}

func GenerateDiagoPanelHTML(data DiagoData) (string, error) {

tpl, err := template.New("diagoPanel").Parse(GetDiagoPanelTemplate())
if err != nil {
return "", err
}

var builder strings.Builder

err = tpl.Execute(&builder, data)
if err != nil {
return "", err
}

return builder.String(), nil
}

type responseWriter struct {
gin.ResponseWriter
buffer *bytes.Buffer
buffer *bytes.Buffer
statusCode int
}

func (w *responseWriter) Write(data []byte) (int, error) {
return w.buffer.Write(data)
}

func (w *responseWriter) WriteHeaderNow() {
if !w.Written() {
w.ResponseWriter.WriteHeaderNow()
}
}

func (w *responseWriter) WriteHeader(statusCode int) {
if w.Written() {
fmt.Sprintf("[WARNING] Headers were already written. Is: %d, try: %d", w.Status(), statusCode)
return
}
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
79 changes: 48 additions & 31 deletions extensions/diagoLatencyExtension.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,50 @@ import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gouef/diago"
"html/template"
"log"
"strings"
"time"
)

type LatencyData struct {
Latency string
}

type DiagoLatencyExtension struct {
startTime time.Time
latency time.Duration
startTime time.Time
latency time.Duration
PanelGenerator diago.PanelGenerator
TemplateProvider diago.TemplateProvider
}

type DefaultLatencyTemplateProvider struct{}

func (p DefaultLatencyTemplateProvider) GetTemplate() string {
return diago.GetDiagoLatencyPanelTemplate()
}

func NewDefaultTemplateProvider() *DefaultLatencyTemplateProvider {
return &DefaultLatencyTemplateProvider{}
}

func NewDiagoLatencyExtension() *DiagoLatencyExtension {
return &DiagoLatencyExtension{}
generator := diago.NewDefaultPanelGenerator()
tmpProvider := NewDefaultTemplateProvider()
return &DiagoLatencyExtension{
PanelGenerator: generator,
TemplateProvider: tmpProvider,
}
}

func (e *DiagoLatencyExtension) SetTemplateProvider(provider diago.TemplateProvider) {
e.TemplateProvider = provider
}

func (e *DiagoLatencyExtension) GetLatency() time.Duration {
return e.latency
}

func (e *DiagoLatencyExtension) SetLatency(latency time.Duration) {
e.latency = latency
}

func (e *DiagoLatencyExtension) GetHtml(c *gin.Context) string {
Expand All @@ -30,20 +61,11 @@ func (e *DiagoLatencyExtension) GetJSHtml(c *gin.Context) string {
func (e *DiagoLatencyExtension) GetPanelHtml(c *gin.Context) string {

var formattedLatency string
switch {
case e.latency > time.Second:
formattedLatency = fmt.Sprintf("%.2f s", float64(e.latency)/float64(time.Second))
case e.latency > time.Millisecond:
formattedLatency = fmt.Sprintf("%.2f ms", float64(e.latency)/float64(time.Millisecond))
case e.latency > time.Microsecond:
formattedLatency = fmt.Sprintf("%.2f µs", float64(e.latency)/float64(time.Microsecond))
default:
formattedLatency = fmt.Sprintf("%.2f ns", float64(e.latency)/float64(time.Nanosecond))
}
formattedLatency = formatLatency(e.latency)

log.Printf("Time: %s", formattedLatency)

result, err := e.generateDiagoPanelHTML(struct{ Latency string }{Latency: formattedLatency})
result, err := e.PanelGenerator.GenerateHTML("diagoLatencyPanel", e.TemplateProvider, LatencyData{Latency: formattedLatency})

if err != nil {
log.Printf("Diago Lattency Extension: %s", err.Error())
Expand All @@ -58,20 +80,15 @@ func (e *DiagoLatencyExtension) AfterNext(c *gin.Context) {
e.latency = time.Since(e.startTime)
}

func (e *DiagoLatencyExtension) generateDiagoPanelHTML(data struct {
Latency string
}) (string, error) {
tpl, err := template.New("diagoLatencyPanel").Parse(diago.GetDiagoLatencyPanelTemplate())
if err != nil {
return "", err
}

var builder strings.Builder

err = tpl.Execute(&builder, data)
if err != nil {
return "", err
func formatLatency(latency time.Duration) string {
switch {
case latency > time.Second:
return fmt.Sprintf("%.2f s", float64(latency)/float64(time.Second))
case latency > time.Millisecond:
return fmt.Sprintf("%.2f ms", float64(latency)/float64(time.Millisecond))
case latency > time.Microsecond:
return fmt.Sprintf("%.2f µs", float64(latency)/float64(time.Microsecond))
default:
return fmt.Sprintf("%.2f ns", float64(latency)/float64(time.Nanosecond))
}

return builder.String(), nil
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.12.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6po
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
Expand Down
52 changes: 52 additions & 0 deletions templateProvider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package diago

import (
"errors"
"html/template"
"strings"
)

type TemplateProvider interface {
GetTemplate() string
}

type PanelGenerator interface {
GenerateHTML(name string, templateProvider TemplateProvider, data interface{}) (string, error)
}

type DefaultPanelGenerator struct{}

type DefaultTemplateProvider struct{}

func (p DefaultTemplateProvider) GetTemplate() string {
return GetDiagoPanelTemplate()
}

func (d *DefaultPanelGenerator) GenerateHTML(name string, templateProvider TemplateProvider, data interface{}) (string, error) {
templateContent := templateProvider.GetTemplate()
tp := template.New(name)
if tp == nil {
return "", errors.New("Bad template name")
}
tpl, err := tp.Parse(templateContent)
if err != nil {
return "", err
}

var builder strings.Builder

err = tpl.Execute(&builder, data)
if err != nil {
return "", err
}

return builder.String(), nil
}

func NewDefaultPanelGenerator() *DefaultPanelGenerator {
return &DefaultPanelGenerator{}
}

func NewDefaultTemplateProvider() *DefaultTemplateProvider {
return &DefaultTemplateProvider{}
}
Loading

0 comments on commit f12e527

Please sign in to comment.