How can I read a header from an http request in golang?

前端 未结 3 1381
闹比i
闹比i 2021-02-02 05:53

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

3条回答
  •  情深已故
    2021-02-02 06:09

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
    )
    
    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 \n", 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\n", k, v)
        }
    
        fmt.Fprintf(w, "Host = %q\n", r.Host)
        fmt.Fprintf(w, "RemoteAddr= %q\n", r.RemoteAddr)
        //Get value for a specified token
        fmt.Fprintf(w, "\n\nFinding value of \"Accept\" %q", r.Header["Accept"])
    }
    

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

提交回复
热议问题