Created
January 26, 2015 22:33
-
-
Save iaintshine/06f882212bc4fd43a8be to your computer and use it in GitHub Desktop.
Passing context between golang's http handlers using unsafe pointer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"net/http/httptest" | |
"unsafe" | |
) | |
type ExtRequest struct { | |
*http.Request | |
message string | |
} | |
func main() { | |
handlerReader := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request){ | |
extReq := (*ExtRequest)(unsafe.Pointer(req)) | |
fmt.Println(extReq.message) | |
w.WriteHeader(http.StatusOK) | |
}) | |
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { | |
extReq := &ExtRequest{req, "this is message passed between handlers"} | |
handlerReader(w, (*http.Request)(unsafe.Pointer(extReq))) | |
}) | |
mux := http.NewServeMux() | |
mux.Handle("/", handler) | |
srv := httptest.NewServer(mux) | |
defer srv.Close() | |
req, _ := http.NewRequest("GET", srv.URL, nil) | |
http.DefaultClient.Do(req) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment