This commit is contained in:
Meutel 2017-07-27 19:57:26 +02:00
parent 909b315bea
commit afcdb97e62
5 changed files with 121 additions and 0 deletions

2
.gitignore vendored
View File

@ -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

23
form-ex1/form.html Normal file
View File

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<head><title>Form ex1</title></head>
<body>
{{ if .first }}
{{ if .last }}
<p>Hello {{ .first }} {{ .last }}</p>
{{ end }}
{{ end }}
<form method="POST">
<label>
First name:
<input type="text" name="first" value="{{ .first }}"/>
</label>
<label>
Last name:
<input type="text" name="last" value="{{ .last }}"/>
</label>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

24
form-ex1/main.go Normal file
View File

@ -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)
}

18
form-ex2/form.html Normal file
View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head><title>Form ex2</title></head>
<body>
{{ if . }}
<p>{{ . }}</p>
{{ else }}
<form method="POST" enctype="multipart/form-data">
<label>
Fichier:
<input type="file" name="file"/>
</label>
<input type="submit" value="Submit"/>
</form>
{{ end }}
</body>
</html>

54
form-ex2/main.go Normal file
View File

@ -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)
}