-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhello-form.go
59 lines (47 loc) · 1.63 KB
/
hello-form.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright 2019 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
import (
"fmt"
"log"
"net/http"
"github.com/chai2010/pbgo"
"github.com/chai2010/pbgo/examples/form.pb"
"github.com/julienschmidt/httprouter"
)
func main() {
router := httprouter.New()
// http://localhost:8080
router.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Header().Add("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, `
<form method="POST" action="/api/comment">
<input type="text" name="user" value="user name">
<input type="email" name="email" value="[email protected]">
<input name="url" value="http://chai2010.cn"></textarea>
<textarea name="text" value="text">www</textarea>
<input type="text" name="next" value="/thanks">
<button type="submit">Send Test</button>
</form>
`)
})
router.GET("/thanks", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprintln(w, "Thanks")
})
// curl -d "user=chai&[email protected]&text=hello&next=http://github.com" localhost:8080/api/comment
router.POST("/api/comment", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var form form_pb.Comment
if err := pbgo.BindForm(r, &form); err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
log.Println("err:", err)
return
}
if form.Next != "" {
http.Redirect(w, r, form.Next, http.StatusFound)
}
log.Println("form:", form)
})
log.Fatal(http.ListenAndServe(":8080", router))
}