Go Web 开发

发布时间: 更新时间: 总字数:602 阅读时间:2m 作者: 分享 复制网址

Golang Web 开发基础介绍

HTTP 协议

HTTP 协议介绍

示例

Web 开发

net/http 包提供了HTTP服务器和客户端的开发实现,内置web服务器。

  • web 服务器开发
    • 定义处理器(函数):接收用户信息,返回响应
      • 处理器:实现 Handler 接口 ServeHTTP(w http.ResponseWriter, r *http.Request)
      • 处理器函数:满足函数签名 func(http.ResponseWriter, *http.Request) 的函数
    • 绑定处理器和url(路由)
      • 绑定处理器:http.Handle(url, &Handler)
      • 绑定处理器函数:http.HandleFunc(url,)
    • 启动服务器:http.ListenAndServe(addr, nil)
  • 客户端开发
    • http.Client 包提供 Get/Post 等方法

  • 文件服务器可以 http.FileServer 发布

示例:httpserver 实现

http 请求类型

  • Post 请求格式:application/x-www-form-urlencoded,解析先调用 ParseForm,然后在如下方法中获取数据:
    • func (r *Request) FormValue(key string) string
    • func (r *Request) PostFormValue(key string) string
  • 上传文件请求格式:multipart/form-data/multipart/mixed,解析先调用 ParseForm,然后获取数据:
    • func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
  • 其他数据,如 application/json,需从 request.Body 中解析

cookie 组成:name: value

  • 向客户端写入 Cookie 的方法 http.SetCookie(w ResponseWriter, cookie *Cookie)
  • 获取 Cookie 的方法
    • Request.Header.Get(“Cookies”)
    • func (r *Request) Cookie(name string) (*Cookie, error)
    • func (r *Request) Cookies() []*Cookie

重定向

func Redirect(w ResponseWriter, r *Request, url string, code int)

示例

Go net 网络模块

文件上传

// https://gist.github.com/andrewmilson/19185aab2347f6ad29f5
package main

import (
  "net/http"
  "os"
  "bytes"
  "path"
  "path/filepath"
  "mime/multipart"
  "io"
)

func main() {
  fileDir, _ := os.Getwd()
  fileName := "upload-file.txt"
  filePath := path.Join(fileDir, fileName)

  file, _ := os.Open(filePath)
  defer file.Close()

  body := &bytes.Buffer{}
  writer := multipart.NewWriter(body)
  part, _ := writer.CreateFormFile("file", filepath.Base(file.Name()))
  io.Copy(part, file)
  writer.Close()

  r, _ := http.NewRequest("POST", "http://example.com", body)
  r.Header.Add("Content-Type", writer.FormDataContentType())
  client := &http.Client{}
  client.Do(r)
}
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数