In my golang application, I'm setting some global variables to true based on form input, and then discovering that they have changed to false when used in a subsequent function. Question, what is the proper way to declare and set Boolean values in golang?
var withKetchup bool
var withMustard bool
func orderProcess(w http.ResponseWriter, r *http.Request){
r.ParseForm()
withKetchup := r.FormValue("withKetchup") //set to true (in form js form selection)
withMustard := r.FormValue("withMustard") //set to true
code omitted ///
}
func prepareOrder(){
code omitted//
fmt.Println(withKetchup, withMustard) //both are false even though initially set to true
if withKetchup == true && withMustard == true{
}else {
}
}
The code
withKetchup := r.FormValue("withKetchup")
declares and sets a local variable of type string using a short variable declaration. To set the global bool variable, convert the statement to an assignment by removing the ":". Also, compute a bool value by comparing the form value with "":
withKetchup = r.FormValue("withKetchup") == "true"
Because the server executes handlers concurrently, it's not safe to use a global variable like this. I suggest passing the values as arguments to prepareOrder:
func orderProcess(w http.ResponseWriter, r *http.Request){
r.ParseForm()
withKetchup := r.FormValue("withKetchup") == "true"
withMustard := r.FormValue("withMustard") == "true"
prepareOrder(withKetchup, withMustard)
}
func prepareOrder(withKetchup, withMustard bool){
if withKetchup == true && withMustard == true{
}else {
}
}