Skip to content

Instantly share code, notes, and snippets.

@iaintshine
Created January 26, 2015 22:33
Show Gist options
  • Save iaintshine/06f882212bc4fd43a8be to your computer and use it in GitHub Desktop.
Save iaintshine/06f882212bc4fd43a8be to your computer and use it in GitHub Desktop.
Passing context between golang's http handlers using unsafe pointer
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