github.com/wtfutil/wtf@v0.43.0/modules/urlcheck/widget.go (about) 1 package urlcheck 2 3 import ( 4 "net/http" 5 "text/template" 6 "time" 7 8 "github.com/rivo/tview" 9 "github.com/wtfutil/wtf/view" 10 ) 11 12 type Widget struct { 13 view.TextWidget 14 15 settings *Settings // settings from the configuration file 16 urlList []*urlResult // list of a collection of useful properies of the url 17 client *http.Client // the http client shared with all the requestes across all the refreshes 18 timeout time.Duration // the timeout for a single request 19 PreparedTemplate *template.Template // the test template shared across the refreshes 20 templateString string // the string needed to parse the template and shared across all the widget refreshes 21 } 22 23 // NewWidget creates and returns an instance of Widget 24 func NewWidget(tviewApp *tview.Application, redrawChan chan bool, settings *Settings) *Widget { 25 maxUrl := len(settings.urls) 26 27 widget := Widget{ 28 TextWidget: view.NewTextWidget(tviewApp, redrawChan, nil, settings.Common), 29 30 settings: settings, 31 urlList: make([]*urlResult, maxUrl), 32 client: &http.Client{}, 33 timeout: time.Duration(settings.requestTimeout) + time.Second, 34 } 35 36 widget.init() 37 widget.View.SetWrap(false) 38 39 return &widget 40 } 41 42 /* -------------------- Exported Functions -------------------- */ 43 44 // Refresh updates the onscreen contents of the widget 45 func (widget *Widget) Refresh() { 46 widget.check() 47 widget.display() 48 } 49 50 /* -------------------- Unexported Functions -------------------- */ 51 52 // The string passed from the settings are checked and prepared for processing 53 func (widget *Widget) init() { 54 55 // Prepare the template for the results 56 widget.PrepareTemplate() 57 58 for i, urlString := range widget.settings.urls { 59 widget.urlList[i] = newUrlResult(urlString) 60 } 61 } 62 63 // Do the actual requests and check the responses at every widget refresh 64 func (widget *Widget) check() { 65 for _, urlRes := range widget.urlList { 66 if urlRes.IsValid { 67 urlRes.ResultCode, urlRes.ResultMessage = DoRequest(urlRes.Url, widget.timeout, widget.client) 68 } 69 } 70 } 71 72 // Format and displays the results at every refresh 73 func (widget *Widget) display() { 74 widget.Redraw(func() (string, string, bool) { 75 return widget.CommonSettings().Title, widget.FormatResult(), false 76 }) 77 }