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
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)
}