github.com/wtfutil/wtf@v0.43.0/modules/urlcheck/view.go (about)

     1  package urlcheck
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"net/http"
     7  	"text/template"
     8  )
     9  
    10  // Prepare the text template at the moment of the widget creation and stores it in the widget instance
    11  func (widget *Widget) PrepareTemplate() {
    12  
    13  	textColor := fmt.Sprintf(" [%s]", widget.settings.Common.Colors.Text)
    14  	labelColor := fmt.Sprintf(" [%s]", widget.settings.Common.Colors.Label)
    15  
    16  	widget.templateString = "{{range .}} " +
    17  		"{{. | getResultColor}}" +
    18  		"[{{if eq .ResultCode 999}}---{{else}}{{.ResultCode}}{{end}}]" +
    19  		textColor + "{{.Url}}" +
    20  		labelColor + "{{.ResultMessage}}" +
    21  		"\n{{end}}"
    22  
    23  	widget.PreparedTemplate = template.New("tmpl").Funcs(template.FuncMap{"getResultColor": getResultColor})
    24  }
    25  
    26  // Parse the results at each refresh of the widge
    27  func (widget *Widget) parseTemplate() *template.Template {
    28  	return template.Must(widget.PreparedTemplate.Parse(widget.templateString))
    29  }
    30  
    31  // Format the parsed results accordingly to the app style
    32  func (widget *Widget) FormatResult() string {
    33  
    34  	if len(widget.urlList) < 1 {
    35  		return "empty URL list"
    36  	}
    37  
    38  	t := widget.parseTemplate()
    39  	resultBuffer := new(bytes.Buffer)
    40  	err := t.Execute(resultBuffer, widget.urlList)
    41  	if err != nil {
    42  		return err.Error()
    43  	}
    44  	return resultBuffer.String()
    45  }
    46  
    47  // URLs with no issues will have their result code in green, otherways in red.
    48  func getResultColor(ur urlResult) string {
    49  	if !ur.IsValid {
    50  		return "[red]"
    51  	}
    52  
    53  	if ur.ResultCode < http.StatusInternalServerError {
    54  		return "[green]"
    55  	}
    56  
    57  	return "[red]"
    58  }