Go语言(十二)web编程

wx5b285b48ed74e · · 531 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

web编程

web编程基础

web的工作方式

Go语言(十二)web编程

http协议介绍

  • http请求体
    Go语言(十二)web编程
  • http响应体
    Go语言(十二)web编程

Web程序开发

  • 基于“net/http”封装的web服务相关的功能
  • 使用简单
func sayhelloName(w http.ResponseWriter,r *http.Request) {
   r.ParseForm()       //参数解析
   fmt.Printf("r.Form:%v\n",r.Form)    
   fmt.Printf("Path:%v\n",r.URL.Path)
   fmt.Printf("Schema:%v\n",r.URL.Scheme)
   fmt.Printf("r.Form[url_long]:%v\n",r.Form["url_long"])

   for k,v := range r.Form{
      fmt.Printf("key=%v\n",k)
      fmt.Printf("val=%v\n",strings.Join(v,""))
   }

   fmt.Fprintf(w,"hello")

}

func main() {
   http.HandleFunc("/",sayhelloName)
   err := http.ListenAndServe(":9090",nil)
   if err != nil {
      log.Fatal("ListenAndServer:",err)
   }
}

golang web服务工作方式

表单提交

  • 通过<form></form>扩起来的区域,允许用户提交数据

  • 用户登录验证小例子
    • login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<form action="/login" method="POST">
    <div>
        <span>用户名:</span>
        <input type="text" name="username">
    </div>
    <div>
        <span>密码:</span>
        <input type="text" name="password">
    </div>
    <div>
        <input type="submit" value="登录">
    </div>
</form>
</body>
</html>
  • AuthFunc.go
func loginFunc(w http.ResponseWriter,r *http.Request) {
   if r.Method == "GET" {
      data,err := ioutil.ReadFile("./login.html")
      if err != nil {
         http.Redirect(w,r,"/404.html",http.StatusNotFound)
         fmt.Errorf("read file faild:err:%v\n",err)
         return
      }
      w.Write(data)
   }else if r.Method == "POST" {
      r.ParseForm()
      username := r.FormValue("username")
      password := r.FormValue("password")
      if username == "admin" && password == "admin" {
         fmt.Fprintf(w,"login success")
      }else {
         fmt.Fprintf(w,"username or password error")
      }
   }
}

func main() {
   http.HandleFunc("/login",loginFunc)
   err := http.ListenAndServe(":9090",nil)
   if err != nil {
      log.Fatal("ListenAndServer:",err)
   }
}

模板介绍与使用

模板替换

  • {{}}来包含需要在渲染时被替换的字段,{{.}}表示当前对象

通过{{.FieldName}} 来访问对象的属性

  • demo.go
var (
   t *template.Template
)

type User struct {
   Name string
   Age  int
}

func initTemplate() (err error){
   //加载模板
   t, err = template.ParseFiles("./index.html")
   if err != nil {
      fmt.Println("parse file error:",err)
      return
   }
   return
}

func handleUserInfo(w http.ResponseWriter,r *http.Request) {
   var user User = User{
      Name: "wanghui",
      Age:  20,
   }

   t.Execute(w,user)
}

func main() {
   err := initTemplate()
   if err != nil {
      return
   }

   http.HandleFunc("/user/info",handleUserInfo)
   err = http.ListenAndServe(":9090",nil)
   if err != nil {
      fmt.Errorf("http start error %v\n",err)
      return
   }
}
  • index.html
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<form action="/login" method="POST">
    <div>
        <span>用户名:{{ .Name }}</span>

    </div>
    <div>
        <span>年龄:{{ .Age }}</span>
    </div>
</form>
</body>
</html>

if判断

  • index.html
<div>
    <span>用户名:{{ .Name }}</span>
</div>
<div>
    <span>年龄:{{ .Age }}</span>
</div>
<div>
    {{ if gt .Age 18 }}
        <p>Hello old man</p>
        {{ else }}
        <p>hello young man</p>
    {{ end }}
</div>

with用法

为了简化结构体嵌套的问题

  • index.html
<body>
<form action="/login" method="POST">
    <div>
        <span>用户名:{{ .Name }}</span>
    </div>
    <div>
        <span>年龄:{{ .Age }}</span>
    </div>
    {{with .Address}}
    <div>
        <span>省:{{.Province}}</span>
    </div>
    <div>
        <span>城市:{{.City}}</span>
    </div>
    <div>
        <span>邮编:{{.Code}}</span>
    </div>
    {{end}}
</form>
</body>
  • server.go
var (
   t *template.Template
)

type Address struct {
   Province string
   City     string
   Code     string
}

type User struct {
   Name    string
   Age     int
   Address Address
}

func initTemplate() (err error){
   //加载模板
   t, err = template.ParseFiles("./index.html")
   if err != nil {
      fmt.Println("parse file error:",err)
      return
   }
   return
}

func handleUserInfo(w http.ResponseWriter,r *http.Request) {
   var user User = User{
      Name: "wanghui",
      Age:  20,
      Address:Address{
         Province: "gansu",
         City:     "zhangye",
         Code:     "734000",
      },
   }
   t.Execute(w,user)
}

func main() {
   err := initTemplate()
   if err != nil {
      return
   }

   http.HandleFunc("/user/info",handleUserInfo)
   err = http.ListenAndServe(":9090",nil)
   if err != nil {
      fmt.Errorf("http start error %v\n",err)
      return
   }
}

range循环语法

  • index.html
<body>
<form action="/login" method="POST">
    {{range .}}
    <div>
        <span>用户名:{{ .Name }}</span>
    </div>
    <div>
        <span>年龄:{{ .Age }}</span>
    </div>
    {{with .Address}}
        <div>
            <span>省:{{.Province}}</span>
        </div>
        <div>
            <span>城市:{{.City}}</span>
        </div>
        <div>
            <span>邮编:{{.Code}}</span>
        </div>
        <hr>
    {{end}}
    {{end}}
</form>
</body>
  • server.go
package main

import (
   "fmt"
   "html/template"
   "net/http"
)

var (
   t *template.Template
)

type Address struct {
   Province string
   City     string
   Code     string
}

type User struct {
   Name    string
   Age     int
   Address Address
}

func initTemplate() (err error) {
   //加载模板
   t, err = template.ParseFiles("./index.html")
   if err != nil {
      fmt.Println("parse file error:", err)
      return
   }
   return
}

func handleUserInfo(w http.ResponseWriter, r *http.Request) {
   var users []*User
   for i := 0; i < 15; i++ {
      var user User = User{
         Name: "wanghui",
         Age:  20,
         Address: Address{
            Province: "gansu",
            City:     "zhangye",
            Code:     "734000",
         },
      }
      users = append(users,&user)
   }

   t.Execute(w, users)
}

func main() {
   err := initTemplate()
   if err != nil {
      return
   }

   http.HandleFunc("/user/info", handleUserInfo)
   err = http.ListenAndServe(":9090", nil)
   if err != nil {
      fmt.Errorf("http start error %v\n", err)
      return
   }
}

有疑问加站长微信联系(非本文作者)

本文来自:51CTO博客

感谢作者:wx5b285b48ed74e

查看原文:Go语言(十二)web编程

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

531 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传