2017-09-03 07:49 阅读 504


If I receive a request of type http.Request, how can I read the value of a specific header? In this case I want to pull the value of a jwt token out of the request header.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    doushan6692 doushan6692 2017-09-03 10:03

    You can use the r.Header.Get:

    func yourHandler(w http.ResponseWriter, r *http.Request) {
        ua := r.Header.Get("User-Agent")
    点赞 评论 复制链接分享
  • dqq9695 dqq9695 2017-09-03 08:56
    package main
    import (
    func main() {
        http.HandleFunc("/", handler)
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
    func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "%s %s %s 
    ", r.Method, r.URL, r.Proto)
        //Iterate over all header fields
        for k, v := range r.Header {
            fmt.Fprintf(w, "Header field %q, Value %q
    ", k, v)
        fmt.Fprintf(w, "Host = %q
    ", r.Host)
        fmt.Fprintf(w, "RemoteAddr= %q
    ", r.RemoteAddr)
        //Get value for a specified token
        fmt.Fprintf(w, "
    Finding value of \"Accept\" %q", r.Header["Accept"])

    Connecting to http://localhost:8000/ from a browser will print the output in the browser.

    点赞 评论 复制链接分享