Skip to content

Commit

Permalink
Don't start a goroutine when not needed
Browse files Browse the repository at this point in the history
sync.Once only has the overhead of a single atomic.LoadUint32

Fixes #693
  • Loading branch information
erikdubbelboer committed Nov 16, 2019
1 parent 32793db commit 32de06d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
10 changes: 8 additions & 2 deletions header.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
"sync"
"sync/atomic"
"time"
)
Expand Down Expand Up @@ -1436,7 +1437,7 @@ func isOnlyCRLF(b []byte) bool {
return true
}

func init() {
func updateServerDate() {
refreshServerDate()
go func() {
for {
Expand All @@ -1446,7 +1447,10 @@ func init() {
}()
}

var serverDate atomic.Value
var (
serverDate atomic.Value
serverDateOnce sync.Once // serverDateOnce.Do(updateServerDate)
)

func refreshServerDate() {
b := AppendHTTPDate(nil, time.Now())
Expand Down Expand Up @@ -1493,6 +1497,8 @@ func (h *ResponseHeader) AppendBytes(dst []byte) []byte {
if len(server) != 0 {
dst = appendHeaderLine(dst, strServer, server)
}

serverDateOnce.Do(updateServerDate)
dst = appendHeaderLine(dst, strDate, serverDate.Load().([]byte))

// Append Content-Type only for non-zero responses
Expand Down
2 changes: 2 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2474,6 +2474,8 @@ func (s *Server) writeFastError(w io.Writer, statusCode int, msg string) {
server = fmt.Sprintf("Server: %s\r\n", s.getServerName())
}

serverDateOnce.Do(updateServerDate)

fmt.Fprintf(w, "Connection: close\r\n"+
server+
"Date: %s\r\n"+
Expand Down

0 comments on commit 32de06d

Please sign in to comment.