package main import ( "encoding/json" "fmt" "log" "net/http" ) //<link rel="stylesheet" href="media/index.css"> func indexHandler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w,r,"index.html") } //http://127.0.0.1:8000/submit func submitHandler(w http.ResponseWriter, r *http.Request) { //获取post json请求转换为map err := r.ParseForm() if err != nil { log.Fatal("parse form error ", err) } // 初始化请求变量结构 formData := make(map[string]interface{}) // 调用json包的解析,解析请求body json.NewDecoder(r.Body).Decode(&formData) //log.Println("req form: ", formData) for key, value := range formData { log.Println("key:", key, " => value :", value) } fmt.Fprintf(w, "submitHandler") } func main() { http.HandleFunc("/", indexHandler) http.HandleFunc("/submit", submitHandler) http.Handle("/media/",http.StripPrefix("/media/",http.FileServer(http.Dir("./media")))) println("web server started sucess") http.ListenAndServe(":8000", nil) }
//media/index.css
body { background-color:#d0e4fe; } h1 { color:orange; text-align:center; } p { font-family:"Times New Roman"; font-size:20px; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <link rel="stylesheet" href="media/index.css"> </head> <body> <h1>CSS 实例!</h1> <p>这是一个段落。</p> </body> </html>
package main import ( "encoding/json" "fmt" "log" "net/http" "text/template" ) //<link rel="stylesheet" href="media/index.css"> func indexHandler(w http.ResponseWriter, r *http.Request) { // 加载html模板 t, _ := template.ParseFiles("index.html") // 准备模板数据 // data := map[string]interface{}{"userName": "irene", "count": 123} // 渲染模板数据并相应页面 t.Execute(w, nil) //http.ServeFile(w,r,"index.html") } //http://127.0.0.1:8000/submit func submitHandler(w http.ResponseWriter, r *http.Request) { //获取post json请求转换为map err := r.ParseForm() if err != nil { log.Fatal("parse form error ", err) } // 初始化请求变量结构 formData := make(map[string]interface{}) // 调用json包的解析,解析请求body json.NewDecoder(r.Body).Decode(&formData) //log.Println("req form: ", formData) for key, value := range formData { log.Println("key:", key, " => value :", value) } fmt.Fprintf(w, "submitHandler") } func main() { http.HandleFunc("/", indexHandler) http.HandleFunc("/submit", submitHandler) http.Handle("/media/",http.StripPrefix("/media/",http.FileServer(http.Dir("./media")))) println("web server started sucess") http.ListenAndServe(":8000", nil) }