Created
January 27, 2017 19:28
-
-
Save groob/b3c49fad984de6e67421f76875297579 to your computer and use it in GitHub Desktop.
go form error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html xmlns="http://www.w3.org/1999/xhtml"> | |
<head> | |
<meta http-equiv="content-type" content="text/html; charset=utf-8"> | |
<title>awesome go project</title> | |
</head> | |
<body> | |
<form class="form-upload" method="post" action="/upload"> | |
<fieldset> | |
<input type="text" name="first_name" /> | |
<span class="error">{{.Error}}</span> | |
<input type="submit" name="submit" value="Submit"> | |
</fieldset> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"html/template" | |
"log" | |
"net/http" | |
) | |
type Server struct { | |
tmpl *template.Template | |
} | |
type Form struct { | |
Error string | |
} | |
func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) { | |
e := Form{Error: "Error: some bad input"} | |
if err := s.tmpl.ExecuteTemplate(w, "index.html", e); err != nil { | |
respondErr(err, w) | |
return | |
} | |
} | |
func (s *Server) index(w http.ResponseWriter, r *http.Request) { | |
if err := s.tmpl.ExecuteTemplate(w, "index.html", nil); err != nil { | |
respondErr(err, w) | |
return | |
} | |
} | |
func respondErr(err error, w http.ResponseWriter) { | |
log.Println(err) | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
func main() { | |
tmpl, err := template.ParseFiles("templates/index.html") | |
if err != nil { | |
log.Fatal(err) | |
} | |
s := &Server{tmpl} | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", s.index) | |
mux.HandleFunc("/upload", s.handleUpload) | |
log.Fatal(http.ListenAndServe(":8089", mux)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment