当在PollingID字段中输入无效的输入时,我试图让我的根页重定向到/ error。它运行良好,甚至在录制时都显示在chrome的“网络”标签中,但实际上从未将页面重定向到localhost:8080 / error。任何帮助表示赞赏。
我已经尝试创建满足if else语句时要调用的单独函数。
func handleVote(w http.ResponseWriter, r *http.Request) {
// define variables
var userTracker []int
var eligible bool
var err error
var PollingID int
var CandidateM int
var CandidateF int
var utIndex int
var m_valid bool
var f_valid bool
// set values from HTML
PollingID, err = strconv.Atoi(r.FormValue("PollingID"))
if err != nil {
log.Fatal(err)
return
}
CandidateM, err = strconv.Atoi(r.FormValue("ChoiceM"))
if err != nil {
log.Fatal(err)
return
}
CandidateF, err = strconv.Atoi(r.FormValue("ChoiceF"))
if err != nil {
log.Fatal(err)
return
}
// handle mutex (force single-threading)
g_mux.Lock()
defer g_mux.Unlock()
// load userTracker into memory
userTracker, err = load_user_tracker()
if err != nil {
log.Fatal(err)
return
}
// verify user eligiblity
eligible = false
for i, id := range userTracker {
if (id == PollingID) && (id > 0) {
eligible = true
utIndex = i
}
}
// if eligible, vote
if eligible {
// scan through candidates.
// iteration 1
for _, val := range g_election.CandidatesM {
if val.CandidateID == CandidateM {
m_valid = true
}
}
for _, val := range g_election.CandidatesF {
if val.CandidateID == CandidateF {
f_valid = true
}
}
// if a candidate ID is invalid, reject
if (m_valid == false) || (f_valid == false) {
log.Println("Rejected vote from PollingID", PollingID, "due to one or more invalid candidate IDs")
return
}
// otherwise, let's continue to cast a vote
userTracker[utIndex] = 0
err = save_user_tracker(userTracker)
if err != nil {
log.Fatal(err)
return
}
for i, val := range g_election.CandidatesM {
if val.CandidateID == CandidateM {
g_election.CandidatesM[i].Tally++
}
}
for i, val := range g_election.CandidatesF {
if val.CandidateID == CandidateF {
g_election.CandidatesF[i].Tally++
}
}
err = save_candidates()
if err != nil {
log.Fatal(err)
return
}
log.Println("Accepted vote from PollingID", PollingID, "for male", CandidateM, "and female", CandidateF)
} else {
if eligible == false {
log.Println("Rejected vote from PollingID", PollingID, "due to an invalid polling ID")
http.Redirect(w, r, "/error", http.StatusFound)
w.Write([]byte("<script>window.alert('Please login')</script>"))
return
}
}
}
func main() {
log.Println("Starting 2019 election system...")
if err := load_candidates(); err != nil {
log.Fatal("load_candidates() failed:", err, "- exiting...")
return
}
http.Handle("/assets/", http.StripPrefix("/assets/",
http.FileServer(http.Dir("./static/assets"))))
http.Handle("/home/", http.StripPrefix("/home/",
http.FileServer(http.Dir("."))))
http.HandleFunc("/error", handleError)
http.HandleFunc("/help", handleHelp)
http.HandleFunc("/tetris", handleTetris)
http.HandleFunc("/2048", handle2048)
http.HandleFunc("/ajaxvote", handleVote)
http.HandleFunc("/results", handleResults)
http.HandleFunc("/", handleRoot)
http.ListenAndServe(":8080", nil)
}