Question:
I'm just starting to develop in Go, and I'm currently studying Go for Web development, so through examples I started a simple Go server:
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
var Nome string
func SetNewName(w http.ResponseWriter, r *http.Request){
fmt.Println("Old Name: "+Nome)
Nome = r.PostFormValue("nome")
fmt.Println("New Name: "+Nome+" \n")
w.Write([]byte("OK"))
}
//Entry point of the program
func main() {
r := mux.NewRouter()
fs := http.FileServer(http.Dir("public"))
r.Handle("/", fs)
r.HandleFunc("/teste-post", SetNewName).Methods("POST")
srv := &http.Server{
Handler: r,
Addr: ":8000",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
In the public folder I have a simple index.html file, where:
1) Require jQuery
2) It has a form
<form id="frm-post-teste">
<input type="text" name="nome">
<input type="submit" id="btn-send" value="Enviar">
</form>
3) And this script:
$("#btn-send").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: window.location.origin+"/teste-post",
data: $("#frm-post-teste").serialize(),
dataType: "JSON"
}).done(function(data){
console.log(data)
});
});
The Problem I've been facing is : Even requests from different browsers, from different devices and even requests made to this example hosted on DigitalOcean, all of them have a strange behavior, it seems that the application only creates a connection, because the Name variable has the value of the past request stored, even though different requests are made by different clients.
This behavior left me extremely confused as the code is simple and I don't know where the error is coming from.
Answer:
This is because of where the variable is defined, when you define:
var Nome string
It becomes global, accessible to everything, therefore not just a connection.
Making:
curl -X POST -d "nome=inkeliz" 127.0.0.1:8000/teste-post
Returns:
Old Name:
New Name: inkeliz
Later:
curl -X POST -d "nome=x" 127.0.0.1:8000/teste-post
Returns:
Old Name: inkeliz
New Name: x
The way around this is to set the local variable, in this case you could do:
func SetNewName(w http.ResponseWriter, r *http.Request){
var nome string
//...
This will result in:
Old Name:
New Name: inkeliz
Old Name:
New Name: x
Another option would be to simply use the :=
, as in:
func SetNewName(w http.ResponseWriter, r *http.Request){
nome := r.PostFormValue("nome")
fmt.Println("New Name: "+nome+" \n")
w.Write([]byte("OK"))
}