关于后端:Go学习二十一HTTP服务端接收参数的几种方式

8次阅读

共计 4106 个字符,预计需要花费 11 分钟才能阅读完成。

1. 获取 GET 参数

1.1 办法列表

办法名 形容
(r *Request) ParseForm() error 判断是否解析传参时出错
(r *Request) FormValue(key string) string 接管指定 key 的参数值

1.2 应用示例

// 服务端代码
package main
import (
    "fmt"
    "net/http"
)
func main() {http.HandleFunc("/login", login)
    _ = http.ListenAndServe(":8888", nil)
}
func login(w http.ResponseWriter, r *http.Request) {
  // 判断参数是否是 Get 申请,并且参数解析失常
    if r.Method == "GET" && r.ParseForm() == nil {
    // 接管参数
        userName := r.FormValue("userName")
        fmt.Printf("userName: %s \n", userName)
        passWord := r.FormValue("passWord")
        fmt.Printf("passWord: %s \n", passWord)
        if userName == ""|| passWord =="" {w.Write([]byte("用户名或明码不能为空"))
        }
        if userName == "admin" && passWord == "1234" {w.Write([]byte("登录胜利!"))
        } else {w.Write([]byte("用户名或明码谬误!"))
        }
    }
}

2. 获取 POST 参数

2.1 接管 POST 参数分以下两种状况

  • 一般的 Post 表单: Content-Type=application/x-www-form-urlencoded
  • 有文件上传的 Post 表单: Content-Type=multipart/form-data

2.2 一般的 Post 表单(r.PostFormValue)

// 服务端代码
package main
import (
    "fmt"
    "net/http"
)
func main() {http.HandleFunc("/login", login)
    _ = http.ListenAndServe(":8888", nil)
}
// 登录
func login(w http.ResponseWriter, r *http.Request) {if r.Method == "POST" && r.ParseForm() == nil {
        // 接管 post 参数
        userName := r.PostFormValue("userName")
        fmt.Printf("userName: %s \n", userName)
        passWord := r.PostFormValue("passWord")
        fmt.Printf("passWord: %s \n", passWord)
        if userName == ""|| passWord =="" {w.Write([]byte("用户名或明码不能为空"))
            return
        }
        if userName == "admin" && passWord == "1234" {w.Write([]byte("登录胜利!"))
            return
        }
        w.Write([]byte("用户名或明码谬误!"))
    } else {w.Write([]byte("以后接口,仅反对 POST 申请!"))
    }
    return
}

2.3 有文件上传的 Post 表单(r.FormFile)

package main
import (
    "fmt"
    "io"
    "net/http"
    "os"
    "path"
)
func main() {http.HandleFunc("/upload", upload)
    _ = http.ListenAndServe(":8888", nil)
}
// 上传文件
func upload(w http.ResponseWriter, r *http.Request) {if r.Method == "POST" && r.ParseForm() == nil {
        // 接管上传文件的参数
        formFile, fileHeader, err := r.FormFile("file")
        if formFile == nil {http.Error(w,"上传的文件不能为空!",http.StatusInternalServerError)
            return
        }
        if err != nil {http.Error(w,err.Error(),http.StatusInternalServerError)
            return
        }
        // 提早敞开文件
        defer formFile.Close()
        // 获取上传文件的名称
        filename := fileHeader.Filename
        fmt.Printf("文件名称: %s \n",filename)
        // 获取文件的后缀
        ext := path.Ext(filename)
        fmt.Printf("文件后缀: %s \n",ext)
        // 创立新文件, 如果同名文件存在,则会清空
        pathName := "public/img"
        if !pathExist(pathName) {err := os.MkdirAll(pathName, os.ModePerm)
            if err != nil {http.Error(w,"创立目录失败:"+ err.Error(),http.StatusInternalServerError)
                return
            }
        }
        newFile, err := os.Create(pathName +"/"+ filename)
        if err != nil {http.Error(w,"创立文件失败:"+ err.Error(),http.StatusInternalServerError)
            return
        }
        defer newFile.Close()
        // 将 formFile 复制到 newFile, 从而实现上传的性能
        written, err := io.Copy(newFile, formFile)
        fmt.Printf("上传后果: %d \n",written)
        if err != nil {http.Error(w,"文件上传失败:"+ err.Error(),http.StatusInternalServerError)
            return
        }
        w.Write([]byte("文件上传胜利!"))
    }
    return
}
// 判断目录是否存在
func pathExist(path string) bool  {_, err := os.Stat(path)
    if err != nil {if os.IsExist(err) {return true}
        return false
    }
    return true
}
运行后果

3. 获取 Cookie 中的值

3.1 cookie 的数据结构

Cookie是一个构造体, 其中有 Cookie 的名和值、domain、过期工夫等信息, 具体定义形式如下所示:

type Cookie struct {
    Name  string // 变量名
    Value string // 变量值
    Path       string    // 设置拜访哪些门路, 应该携带这个 cookie, 不设置则代表所有
    Domain     string    // 设置拜访域名范畴的主机时, 应该携带这个 cookie, 不设置则代表所有
    Expires    time.Time // 一个工夫值,代表什么时候过期
    RawExpires string    // for reading cookies only
    MaxAge   int // 用来设置过期,为正数或等于 0 示意立刻过期,大于 0 示意过多少秒之后过期
    Secure   bool
    HttpOnly bool
    SameSite SameSite
    Raw      string
    Unparsed []string // Raw text of unparsed attribute-value pairs}

3.2 应用示例

package main
import (
    "encoding/base64"
    "fmt"
    "net/http"
)
func main() {http.HandleFunc("/setCookie", setCookie)
    http.HandleFunc("/getCookie", getCookie)
    _ = http.ListenAndServe(":8888", nil)
}

// 设置 cookie 中的值
func setCookie(w http.ResponseWriter, r *http.Request)  {
    cookie1 := http.Cookie{
        Name:   "uid",
        Value:  "10001",
        MaxAge: 3600, // 一小时后过期
    }
    name := base64.URLEncoding.EncodeToString([]byte("张三"))
    cookie2 := http.Cookie{
        Name:   "name",
        Value:  name,
        MaxAge: 3600, // 一小时后过期
    }
    http.SetCookie(w,&cookie1)
    http.SetCookie(w,&cookie2)
    w.Write([]byte("cookie 已设置!"))
}
// 获取 cookie 中的值
func getCookie(w http.ResponseWriter, r *http.Request) {key := r.FormValue("key")
    if key == "" {http.Error(w,"key 不能为空!",http.StatusInternalServerError)
        return
    }
    cookie, err := r.Cookie(key)
    if err != nil {http.Error(w,"获取失败:" + err.Error(),http.StatusInternalServerError)
        return
    }
    result := make([]string,2)
    result[0] = cookie.Value
    decodeString, _ := base64.URLEncoding.DecodeString(cookie.Value)
    result[1] = string(decodeString)
    fmt.Println(result)
    w.Write([]byte("cookie 已获取!"))
}

微信搜寻关注【猿码记】查看更多文章。

本文由 mdnice 多平台公布

正文完
 0