Go language web programming

web programming

Fundamentals of web programming

How the web works

http protocol introduction

  • http request body
  • http response body

Web program development

  • web services related functions based on "net/http" encapsulation
  • Easy to use
func sayhelloName(w http.ResponseWriter,r *http.Request) {
   r.ParseForm()       //Parameter parsing
   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)
   }
}

How golang web services work

Form submission

  • Allow users to submit data through an expanded area of & lt; form & gt; & lt; / form & gt

  • Small example of user login authentication
    • login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<form action="/login" method="POST">
    <div>
        <span>User name:</span>
        <input type="text" name="username">
    </div>
    <div>
        <span>Password:</span>
        <input type="text" name="password">
    </div>
    <div>
        <input type="submit" value="Sign in">
    </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)
   }
}

Introduction and use of template

Template replacement

  • {{} to contain fields that need to be replaced at render time, {{.} represents the current object

Use {. FieldName}} to access the properties of an object

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

type User struct {
   Name string
   Age  int
}

func initTemplate() (err error){
   //Loading template
   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>User name:{{ .Name }}</span>

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

if judgement

  • index.html
<div>
    <span>User name:{{ .Name }}</span>
</div>
<div>
    <span>Age:{{ .Age }}</span>
</div>
<div>
    {{ if gt .Age 18 }}
        <p>Hello old man</p>
        {{ else }}
        <p>hello young man</p>
    {{ end }}
</div>

with usage

In order to simplify the nesting of structures

  • index.html
<body>
<form action="/login" method="POST">
    <div>
        <span>User name:{{ .Name }}</span>
    </div>
    <div>
        <span>Age:{{ .Age }}</span>
    </div>
    {{with .Address}}
    <div>
        <span>Province:{{.Province}}</span>
    </div>
    <div>
        <span>City:{{.City}}</span>
    </div>
    <div>
        <span>Zip code:{{.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){
   //Loading template
   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 loop syntax

  • index.html
<body>
<form action="/login" method="POST">
    {{range .}}
    <div>
        <span>User name:{{ .Name }}</span>
    </div>
    <div>
        <span>Age:{{ .Age }}</span>
    </div>
    {{with .Address}}
        <div>
            <span>Province:{{.Province}}</span>
        </div>
        <div>
            <span>City:{{.City}}</span>
        </div>
        <div>
            <span>Zip code:{{.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) {
   //Loading template
   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
   }
}

Tags: Go Programming

Posted on Thu, 16 Apr 2020 08:30:28 -0700 by valshooter