addUser.html
<h1>Hello</h1>
<form action='user' method='post'>
<input type=text name=Id /></br>
<input type=text name=name /></br>
<input type=submit />
</form>
<a href="users">Show All</a>
---
package main
import (
//"database/sql"
//_ "github.com/mattn/go-sqlite3"
"fmt"
"html/template"
"log"
"net/http"
"strconv"
)
type User struct {
ID int
Name string
}
func (user User) String() string {
format := `ID : %d Name: %s`
return fmt.Sprintf(format, user.ID, user.Name)
}
func saveUser(w http.ResponseWriter, req *http.Request) {
userId, _ := strconv.Atoi(req.FormValue("Id"))
name := req.FormValue("name")
out := strconv.Itoa(userId) + "-" + name
u := &User{ID: userId, Name: name}
log.Println(out)
fmt.Fprintf(w, u.String())
}
func addUser(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("tmpl/addUser.html")
t.Execute(w, nil)
}
func main() {
http.HandleFunc("/", addUser)
http.HandleFunc("/user", saveUser)
err := http.ListenAndServe(":8880", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
有疑问加站长微信联系(非本文作者)