better request copy code

With state's lock as a pointer, we can use the `*r = *r2` statement for
copying which is much more concise and future proof.
This commit is contained in:
John Eikenberry 2018-02-06 12:22:08 -08:00
parent 50208af173
commit 353daee2bc
2 changed files with 14 additions and 12 deletions

View File

@ -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
}

View File

@ -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.
//
@ -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
}