diff --git a/.gitignore b/.gitignore index 93e27da..8961656 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,5 @@ tpl-text/tpl-text tpl-ex1/tpl-ex1 tpl-ex2/tpl-ex2 tpl-ex3/tpl-ex3 +form-ex1/form-ex1 +form-ex2/form-ex2 diff --git a/form-ex1/form.html b/form-ex1/form.html new file mode 100644 index 0000000..0d02926 --- /dev/null +++ b/form-ex1/form.html @@ -0,0 +1,23 @@ + + +
Hello {{ .first }} {{ .last }}
+ {{ end }} + {{ end }} + + + + diff --git a/form-ex1/main.go b/form-ex1/main.go new file mode 100644 index 0000000..6400d1e --- /dev/null +++ b/form-ex1/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "html/template" + "net/http" +) + +func handleForm(res http.ResponseWriter, req *http.Request) { + data := map[string]string{ + "first": req.FormValue("first"), + "last": req.FormValue("last"), + } + tpl, err := template.ParseFiles("form.html") + if err != nil { + http.Error(res, err.Error(), 500) + } else { + tpl.Execute(res, data) + } +} + +func main() { + http.HandleFunc("/", handleForm) + http.ListenAndServe(":9000", nil) +} diff --git a/form-ex2/form.html b/form-ex2/form.html new file mode 100644 index 0000000..b493db9 --- /dev/null +++ b/form-ex2/form.html @@ -0,0 +1,18 @@ + + +{{ . }}
+ {{ else }} + + {{ end }} + + + diff --git a/form-ex2/main.go b/form-ex2/main.go new file mode 100644 index 0000000..8f4dbeb --- /dev/null +++ b/form-ex2/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + "html/template" + "io" + "log" + "net/http" + "os" + "path/filepath" +) + +func handle(path string, handleFunc func(res http.ResponseWriter, req *http.Request) error) { + http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) { + err := handleFunc(res, req) + if err != nil { + log.Println(err) + http.Error(res, err.Error(), 500) + } + }) +} + +func handleForm(res http.ResponseWriter, req *http.Request) error { + tpl, err := template.ParseFiles("form.html") + if err != nil { + return err + } + var msg string + if req.Method == http.MethodPost { + file, header, err := req.FormFile("file") + if err != nil { + return err + } + + tmpFile, err := os.Create(filepath.Join(os.TempDir(), header.Filename)) + if err != nil { + return err + } + defer tmpFile.Close() + + sz, err := io.Copy(tmpFile, file) + if err != nil { + return err + } + msg = fmt.Sprintf("File uploaded (%d bytes)", sz) + } + tpl.Execute(res, msg) + return nil +} + +func main() { + handle("/", handleForm) + http.ListenAndServe(":9000", nil) +}