Giter VIP home page Giter VIP logo

context's Introduction

gorilla/context

License testing codecov godoc sourcegraph OpenSSF Best Practices

Gorilla Logo

⚠⚠⚠ Note ⚠⚠⚠ gorilla/context, having been born well before context.Context existed, does not play well with the shallow copying of the request that http.Request.WithContext (added to net/http Go 1.7 onwards) performs.

Using gorilla/context may lead to memory leaks under those conditions, as the pointers to each http.Request become "islanded" and will not be cleaned up when the response is sent.

You should use the http.Request.Context() feature in Go 1.7.

gorilla/context is a general purpose registry for global request variables.

  • It stores a map[*http.Request]map[interface{}]interface{} as a global singleton, and thus tracks variables by their HTTP request.

License

See the LICENSE file for details.

context's People

Contributors

adammck avatar andrewsmedina avatar areski avatar coreydaley avatar dmitrybochkarev avatar elithrar avatar kisielk avatar lk4d4 avatar moraes avatar pjvds avatar tylerb avatar yuokada avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

context's Issues

Create annotated tags for releases

Hi

It would be great if you tagged the current HEAD with v1.0.0, and in the future, occasionally bump the version and make new tags with new releases. I suggest using the semver.org versioning scheme, where you have major.minor.patch, and you bump the major for incompatible changes and the minor for compatible changes to the API.

There are already tags in your other repo, https://github.com/gorilla/mux

request-oriented mutex

I notice that there is only one mutex in the context package. I assume if some request call context.Set and therefore hold the write lock, at that moment, any other request will have to wait for it while they don't need to, since the context is request-oriented and preventing race conditions between requests is not its concern. Would it be nice if we let each request have its own mutex.

var (
    mutexes = make(map[http.Request]sync.RWMutex)
    data  = make(map[*http.Request]map[interface{}]interface{})
    datat = make(map[*http.Request]int64)
)

better name: registry

I'd like to duplicate this package using a new name: "registry". Because that's what a context really is.

The context package can be kept available for who is using it, but we favor the new name internally and in the site links and docs.

Worthless? :)

How to access object property after it's passed through context.

Hi. I'm facing a problem that I passed my object through the context. I get it but I can't access it own property.
here is my code.
I define my struct

type Config  struct{
    DbName  string
    DbHost string
        ApiKey string
}

next I init the object

_config = Config{"my_db_name","127.0.0.1","top-secret"}

In first handler I set to the context

context.Set(r, "config", config)

And I get it from next handler

    _config := context.Get(r, "config")
     test_config, found := _config.(config.Config)

     if found{
      fmt.Println(  "wrong" ) 
     }

     fmt.Println( test_config.DbName)

and I see test_config.DbName is empty. when I tried to dump as json string, it's still print value correctly.
For now, I have only a way is encode and decode json again and it worked but it make slow down my code for parsing time.
Any Idea to fix this ?
Thank

mux.go:12: can't find import: "github.com/gorilla/context"

Not sure how to fix this, but I keep getting this error on Windows when I try to get any package using context

D:\Développement\golang\src\github.com>go install github.com/gorilla/pat
# github.com/gorilla/mux
D:\Developpement\golang\src\github.com\gorilla\mux\mux.go:12: can't find import: "github.com/gorilla/context"

Any idea how I can prevent this?

Document Conflict between gorilla/context & Go 1.7's http.Request.WithContext()

RE: gorilla/mux#182

OK, so this happens because r.WithContext() in Go 1.7, which gorilla/mux uses in Go 1.7, creates a shallow copy of the request: https://github.com/golang/go/blob/master/src/net/http/request.go#L288-L298

This shallow copy, as you'd expect, changes the address of the request in gorilla/context's map[*http.Request]map..., effectively islanding any context values.

This is a shortcoming in gorilla/context: any library, mux included, will break it come Go 1.7 and the http.Request.WithContext() method.`

I'm not sure if there's a clean way to fix this: one option would be to call context.GetAll to copy all values from the old request before we call WithContext, and then save them back into the (shallow) copy, but if you have private types as keys (which is recommended), then we can't reliably achieve that. It would also add context back as a dependency to mux.

  • Add a warning to the README
  • Document public API so that godoc users also notice the warning when using getters/setters.

cc/ @kisielk

Why not use official clean func?

I read your source code. And I see the CleanPath function.
I guess it has the same effect with the Clean function in package path or path/filepath that golang supported itself.
Why not use it directly? Why write this function yourself? Any differences between these functions?

I can't get real data from context.Get by go1.8

In the process of using this package, I found that when using the Context.Get method of context to get some data in the HTTP Request, data[r] can't get the request information always. After testing, I found that the HTTPRequest pointer is different to the key of Data[]. The key does not match, this problem did not occur in go1.6, BUT go1.8 has this problem, what happened in the end caused this problem?

CODE
data = make(map[*http.Request]map[interface{}]interface{})func Get(r *http.Request, key interface{}) interface{} {
mutex.RLock()
fmt.Printf("%p\n",r)
fmt.Println("[debug]---------\n",data,"[debug]-----------\n",data[r])
if ctx := data[r]; ctx != nil {
value := ctx[key]
mutex.RUnlock()
return value
}
mutex.RUnlock()
return nil
}

THIS IS MY TEST RESULT>

2018/08/09 10:51:48 ### GET [::1]:48878 localhost:9003 /asset/owner ###
pointer :0xc42000ed30
[debug]--------- map[0xc4201dfc00:map[user:{ jackson [email protected]} token:MTUzMzc4MDYxNXxEdi1CQkFFQ180SUFBUXdCRUFBQU5mLUNBQUVGZEc5clpXNEdjM1J5YVc1bkRDSUFJRFF5WTJJMFpUa3pZemxoTjJFNE1EY3paVFJqTjJReVpHRmpaVGMzTXpGa3yTiUR-1SH6BOxLrBwS7ge8kMAjRq7xCtB68qCtnBtOoA==]]
[debug]--------- map[]

Index on arbitrary keys?

I currently have a helper that is used to render to a http.ResponseWriter. Currently, the renderer is built conditionally on parameters in the request in a middleware far away from the request handling code. The result is that I could have relatively clean handler code like this:

func SearchHandler (w http.ResponseWriter, req *http.Request) {
  someResult := <do some stuff that doesn't ever fail>
  renderJSON(w, http.StatusOK, someResult)
}

However, if I want to access the context created by the middleware, I also need to have req passed to renderJSON just to get the context.

If instead, I could key the context based on the http.ResponseWriter, I would be able to keep my signatures cleaner.

Perhaps there are other solutions here too that involve completely different patterns than I'm currently using.

Is GetAll safe?

Disclaimer: newbie to Golang

From my primitive observation on GetAll the mutex only makes it safe on looking up the Request, returning the underlying context for that request essentially makes the map associated with that request freely mutable, thus if callee A is iterating over the map returned by GetAll and callee B is using Set("k","v") then we've in trouble?. Shouldnt there be some form of shallow copy here?

https://github.com/gorilla/context/blob/master/context.go#L54

Feel free to immediately closed this bug, mark as stupid or downvote if Ive missed something fundamental here..

Why need key

Hi
Why do I need a key to set context?
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.