Skip to content

Commit

Permalink
fix: fix minor race in url template
Browse files Browse the repository at this point in the history
  • Loading branch information
docmerlin committed Aug 27, 2020
1 parent 57a2662 commit 4909d46
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
3 changes: 2 additions & 1 deletion services/httppost/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io/ioutil"
"net/url"
"path"
"strings"
"text/template"

"github.com/pkg/errors"
Expand Down Expand Up @@ -62,7 +63,7 @@ func (c Config) Validate() error {
if err != nil {
return errors.Wrapf(err, "invalid URL template syntax %q", c.URLTemplate)
}
buf := &bytes.Buffer{}
buf := &strings.Builder{}
if err = urlTemplate.Execute(buf, nil); err != nil {
return errors.Wrapf(err, "invalid URL template syntax %q", c.URLTemplate)
}
Expand Down
13 changes: 7 additions & 6 deletions services/httppost/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
"text/template"

Expand All @@ -30,7 +31,7 @@ type Diagnostic interface {
// Only one of name and url should be non-empty
type Endpoint struct {
mu sync.RWMutex
urlTemplate template.Template
urlTemplate *template.Template
headers map[string]string
auth BasicAuth
alertTemplate *template.Template
Expand All @@ -40,7 +41,7 @@ type Endpoint struct {

func NewEndpoint(urlt *template.Template, headers map[string]string, auth BasicAuth, at, rt *template.Template) *Endpoint {
return &Endpoint{
urlTemplate: *urlt,
urlTemplate: urlt,
headers: headers,
auth: auth,
alertTemplate: at,
Expand All @@ -61,7 +62,7 @@ func (e *Endpoint) Update(c Config) error {
if err != nil {
return err
}
e.urlTemplate = *ut
e.urlTemplate = ut
e.headers = c.Headers
e.auth = c.BasicAuth
at, err := c.getAlertTemplate()
Expand Down Expand Up @@ -92,7 +93,7 @@ func (e *Endpoint) RowTemplate() *template.Template {
func (e *Endpoint) URL() *template.Template {
e.mu.RLock()
defer e.mu.RUnlock()
return &e.urlTemplate
return e.urlTemplate
}

func (e *Endpoint) NewHTTPRequest(body io.Reader, tmplCtx interface{}) (req *http.Request, err error) {
Expand All @@ -101,7 +102,7 @@ func (e *Endpoint) NewHTTPRequest(body io.Reader, tmplCtx interface{}) (req *htt
if e.closed {
return nil, errors.New("endpoint was closed")
}
eURL := &bytes.Buffer{}
eURL := &strings.Builder{}
if err = e.URL().Execute(eURL, tmplCtx); err != nil {
return nil, errors.Wrap(err, "failed to execute url template")
}
Expand Down Expand Up @@ -242,7 +243,7 @@ func (s *Service) Test(options interface{}) error {
// Create the HTTP request
var req *http.Request
e := &Endpoint{
urlTemplate: *ut,
urlTemplate: ut,
headers: o.Headers,
}
req, err = e.NewHTTPRequest(body, ad)
Expand Down

0 comments on commit 4909d46

Please sign in to comment.