Hello everyone! I want to test my application on golang, namely the function of adding a new user. The idea is this: I count the number of users, create a request to add a new one, then count again the number of users, which should be +1. I can not figure out how to implement the request with filling out the form of this type:

<form method="POST" action="useraded"> <label>Enter firstname</label><br> <input type="text" name="firstname" /><br><br> 

handlers.go

  func AddNewUserFunc(w http.ResponseWriter, r *http.Request) { //creating new instance and checking method newUser := &model.User{} if r.Method == "GET" { t, _ := template.ParseFiles("templates/addNewUser.html") t.Execute(w, nil) } else { resBool, errStr := checkFormValue(w, r, "firstname", "lastname") if resBool == false { t, err := template.ParseFiles("templates/notSucceded.html") checkError(err) t.Execute(w, errStr) return } newUser.FirstName = r.FormValue("firstname") newUser.LastName = r.FormValue("lastname") var err error newUser.Balance, err = strconv.ParseFloat(r.FormValue("balance"), 64) checkError(err) //open file file, err := os.OpenFile("list.json", os.O_RDWR, 0644) checkError(err) defer file.Close() //read file and unmarshall json file to slice of users b, err := ioutil.ReadAll(file) var alUsrs model.AllUsers err = json.Unmarshal(b, &alUsrs.Users) checkError(err) max := 0 //generation of id(last id at the json file+1) for _, usr := range alUsrs.Users { if usr.Id > max { max = usr.Id } } id := max + 1 newUser.Id = id //appending newUser to slice of all Users and rewrite json file alUsrs.Users = append(alUsrs.Users, newUser) newUserBytes, err := json.MarshalIndent(&alUsrs.Users, "", " ") checkError(err) ioutil.WriteFile("list.json", newUserBytes, 0666) http.Redirect(w, r, "/", 301) } } //index page handler func IndexFunc(w http.ResponseWriter, r *http.Request) { au := model.ShowAllUsers() t, err := template.ParseFiles("templates/indexPage.html") checkError(err) t.Execute(w, au) } //function to delete user func DeleteUserFunc(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { t, _ := template.ParseFiles("templates/deleteUser.html") t.Execute(w, nil) } else { r.ParseForm() id, err := strconv.Atoi(r.FormValue("id")) checkError(err) //open file with users file, err := os.OpenFile("list.json", os.O_RDWR|os.O_APPEND, 0666) defer file.Close() //read file and unmarshall json to []users b, err := ioutil.ReadAll(file) var alUsrs model.AllUsers err = json.Unmarshal(b, &alUsrs.Users) checkError(err) var allID []int for _, usr := range alUsrs.Users { allID = append(allID, usr.Id) } for i, usr := range alUsrs.Users { if model.IsValueInSlice(allID, id) != true { http.Redirect(w, r, "/deleteuser/notsuccededdelete", 302) return } if usr.Id != id { continue } else { alUsrs.Users = append(alUsrs.Users[:i], alUsrs.Users[i+1:]...) } } newUserBytes, err := json.MarshalIndent(&alUsrs.Users, "", " ") checkError(err) ioutil.WriteFile("list.json", newUserBytes, 0666) http.Redirect(w, r, "/deleted", 301) } } //show user by it ID func ShowUserFunc(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { t, _ := template.ParseFiles("templates/showUserPage.html") t.Execute(w, nil) } else { id, err := strconv.Atoi(r.FormValue("id")) checkError(err) var alUsrs model.AllUsers file, err := os.OpenFile("list.json", os.O_RDONLY, 0666) checkError(err) b, err := ioutil.ReadAll(file) checkError(err) json.Unmarshal(b, &alUsrs.Users) var allID []int for _, usr := range alUsrs.Users { allID = append(allID, usr.Id) } for _, usr := range alUsrs.Users { if model.IsValueInSlice(allID, id) != true { http.Redirect(w, r, "/showuser/notsuccededshow/", 302) return } if usr.Id != id { continue } else { t, err := template.ParseFiles("templates/showUserPage.html") checkError(err) t.Execute(w, usr) } } } } 

main.go

  package main import ( "fmt" "net/http" "net/url" "test_Backend_ExpertSender/handlers" ) func main() { http.HandleFunc("/addnewuser/", handlers.AddNewUserFunc) http.HandleFunc("/notsucceded", handlers.NotSucceded) http.HandleFunc("/deleted", handlers.DeletedFunc) http.HandleFunc("/deleteuser/deleted", handlers.DeleteUserFunc) http.HandleFunc("/deleteuser/", handlers.DeleteUserServe) http.HandleFunc("/deleteuser/notsuccededdelete", handlers.NotSuccededDelete) http.HandleFunc("/", handlers.IndexFunc) http.HandleFunc("/showuser/show", handlers.ShowUserFunc) http.HandleFunc("/showuser/", handlers.ShowUser) http.HandleFunc("/showuser/notsuccededshow/", handlers.NotSuccededShow) http.ListenAndServe(":8080", nil) } 

model.go

  package model import ( "encoding/json" "fmt" "io/ioutil" "os" ) func checkError(err error) { if err != nil { fmt.Println(err) } } //function which return is there a value in slice func IsValueInSlice(slice []int, value int) (result bool) { for _, n := range slice { if n == value { return true } } return false } type User struct { Id int `json:"id"` FirstName string `json:"firstName"` LastName string `json:"lastName"` Balance float64 `json:"balance"` } type AllUsers struct { Users []*User } func ShowAllUsers() (au *AllUsers) { file, err := os.OpenFile("list.json", os.O_RDWR|os.O_APPEND, 0666) checkError(err) b, err := ioutil.ReadAll(file) var alUsrs AllUsers json.Unmarshal(b, &alUsrs.Users) checkError(err) return &alUsrs } 
  • 2
    And where is the go code? 😀 What have you tried? - biosckon
  • @biosckon I honestly did not even find which way to go, formValue reads the input, thought to use postFormValue, but this sort of parses the request itself, can this be somehow implemented using the request methods? - Dmitry Milevsky
  • Show us your app on Go. And then we can think. You ask about Go code tests and show HTML. - biosckon
  • @biosckon done) true, I think there will be even more questions) - Dmitry Milevsky
  • Voted for rediscovery. How to open, write the answer. - Ainar-G

1 answer 1

You can test handlers, like this:

main.go

 package main import ( "log" "net/http" ) func main() { http.HandleFunc("/", IndexFunc) log.Fatal(http.ListenAndServe(":8080", nil)) } 

handlers.go

 package main import ( "fmt" "net/http" ) func IndexFunc(w http.ResponseWriter, r *http.Request) { firstName := r.FormValue("firstname") lastName := r.FormValue("lastname") _, err := w.Write([]byte(fmt.Sprintf("%s %s", firstName, lastName))) if err != nil { w.WriteHeader(http.StatusInternalServerError) } w.WriteHeader(http.StatusInternalServerError) } 

handlers_test.go

 package main import ( "bytes" "net/http" "net/http/httptest" "net/url" "testing" ) func TestIndexFunc(t *testing.T) { rw := httptest.NewRecorder() form := url.Values{} form.Add("firstname", "Иван") form.Add("lastname", "Петров") req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString(form.Encode())) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") // Вызов handler IndexFunc IndexFunc(rw, req) if rw.Result().StatusCode != http.StatusOK { t.Errorf("Request code %v not equal code 200", rw.Code) } if rw.Body.String() != "Иван Петров" { t.Errorf(`Request body "%v" not equal body "Иван Петров"`, rw.Body.String()) } }