使用Golang的Context管理上下文的方法

2020-01-28 14:16:59于海丽

golang 1.7版本中context库被很多标准库的模块所使用,比如net/http和os的一些模块中,利用这些原生模块,我们就不需要自己再写上下文的管理器了,直接调用函数接口即可实现,利用context我们可以实现一些比如请求的声明周期内的变量管理,执行一些操作的超时等等。

保存上下文对象

这里我们通过一个简单的例子来看一下如何使用context的特性来实现上下文的对象保存,这里我们写了一个简单的http server,具有登录和退出,状态检查路由(检查用户是否登录)


func main(){
  mux:=http.NewServeMux()
  mux.HandleFunc("/",StatusHandler)
  mux.HandleFunc("/login",LoginHandler)
  mux.HandleFunc("/logout",LogoutHandler)
  contextedMux:=AddContextSupport(mux)
  log.Fatal(http.ListenAndServe(":8080",contextedMux))
}

其中的AddContextSupport是一个中间件,用来绑定一个context到原来的handler中,所有的请求都必须先经过该中间件后才能进入各自的路由处理中。具体的实现代码如下:


func AddContextSupport(next http.Handler)http.Handler{
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    log.Println(r.Method, "-", r.RequestURI)
    cookie, _ := r.Cookie("username")
    if cookie != nil {
      ctx := context.WithValue(r.Context(), "username", cookie.Value)
      // WithContext returns a shallow copy of r with its context changed
      // to ctx. The provided ctx must be non-nil.
      next.ServeHTTP(w, r.WithContext(ctx))
    } else {
      next.ServeHTTP(w, r)
    }
  })
}

该中间件可以打印每次请求的方法和请求的url,然后获得请求的cookie值,如果cookie为空的话则继续传递到对应的路由处理函数中,否则保存cookie的值到Context, 注意这里的Context()是request对象的方法, 将创建一个新的上下文对象(如果context为空),context.WithValue()函数将key和value保存在新的上下文对象中并返回该对象。

其余的路由处理函数代码如下, 分别用来保存cookie的登录路由LoginHandler(),还有删除cookie的退出路由处理函数LogoutHandler()。


func LoginHandler(w http.ResponseWriter,r *http.Request){
  expitation := time.Now().Add(24*time.Hour)
  var username string
  if username=r.URL.Query().Get("username");username==""{
    username = "guest"
  }
  cookie:=http.Cookie{Name:"username",Value:username,Expires:expitation}
  http.SetCookie(w,&cookie)
}

func LogoutHandler(w http.ResponseWriter, r *http.Request) {
  expiration := time.Now().AddDate(0, 0, -1)
  cookie := http.Cookie{Name: "username", Value: "alice_cooper@gmail.com", Expires: expiration}
  http.SetCookie(w, &cookie)
}

这里我们在请求/login的时候,可以传递一个参数username到函数中,比如/login?username=alice , 默认为”guest”用户. 设置的cookie有效期为1天,删除的时候我们只需要设置cookie为之前的日期即可。