emicklei / go-restful

package for building REST-style Web Services using Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A bug that mutates a not-used copy of a struct

shivanshuraj1333 opened this issue · comments

At https://github.com/emicklei/go-restful/blob/v3/route.go#L176-L178
Here Route is struct which will be copied by value. The mutation on the value receiver r doesn't do anything to the original struct in the caller. As a consequence, this mutation has no meaningful effect.

type Route struct {
	Method   string
	...
	contentEncodingEnabled *bool
}

func (r Route) EnableContentEncoding(enabled bool) {
	r.contentEncodingEnabled = &enabled
}

One fix is to use pointer receiver.

func (r *Route) EnableContentEncoding(enabled bool) {
	r.contentEncodingEnabled = &enabled
}

Another possible fix is to write back enabled into the caller'scontentEncodingEnabled :

func (r Route) EnableContentEncoding(enabled bool) {
	*r.contentEncodingEnabled = enabled
}

How to reproduce it (as minimally and precisely as possible):
A simplified bug reproducer is available at: https://play.golang.org/p/cibNCyIarZS

Initially filled in Kubernetes