Skip to content

Commit

Permalink
better request copy code
Browse files Browse the repository at this point in the history
With state's lock as a pointer, we can use the `*r = *r2` statement for
copying which is much more concise and future proof.
  • Loading branch information
eikenb committed Feb 6, 2018
1 parent 50208af commit 353daee
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
3 changes: 2 additions & 1 deletion request-server.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ func (rs *RequestServer) getRequest(handle, method string) (*Request, bool) {
if !ok || r.Method == method { // re-check needed b/c lock race
return r, ok
}
r = &Request{Method: method, Filepath: r.Filepath, state: r.state}
r = r.copy()
r.Method = method
rs.openRequests[handle] = r
return r, ok
}
Expand Down
23 changes: 12 additions & 11 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ func NewRequest(method, path string) *Request {
state: state{RWMutex: new(sync.RWMutex)}}
}

// shallow copy of existing request
func (r *Request) copy() *Request {
r.state.Lock()
defer r.state.Unlock()
r2 := new(Request)
*r2 = *r
return r2
}

// Context returns the request's context. To change the context,
// use WithContext.
//
Expand All @@ -86,17 +95,9 @@ func (r *Request) WithContext(ctx context.Context) *Request {
if ctx == nil {
panic("nil context")
}
r.state.Lock()
defer r.state.Unlock()
r2 := &Request{
Method: r.Method,
Filepath: r.Filepath,
Target: r.Target,
Flags: r.Flags,
Attrs: r.Attrs,
state: r.state,
ctx: ctx,
}
r2 := r.copy()
r2.ctx = ctx
r2.cancelCtx = nil
return r2
}

Expand Down

0 comments on commit 353daee

Please sign in to comment.