I'm now starting to develop in Go, and I'm currently studying Go for Web development, so through examples I've started a simple server in Go:
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) Request 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 for this example hosted on DigitalOcean, all display strange behavior, apparently the only application creates a connection because the Name variable has the value of the last stored request, even though they are different requests made by different clients.
This behavior has left me extremely confused because the code is simple and I do not know where the error is coming from.