gin-gonic / contrib Goto Github PK
View Code? Open in Web Editor NEWCollection of middlewares created by the community
Home Page: https://gin-gonic.github.io/gin/
License: MIT License
Collection of middlewares created by the community
Home Page: https://gin-gonic.github.io/gin/
License: MIT License
Would be great if there's a way to change the delims "{{}}" to something else so it won't conflict w/ Angularjs templates. Currently, I don't see a way to change it.
Hi, I have created rollbar middleware to integrate with rollbar error monitoring for Gin here: https://github.com/easonlin404/rollbar
And this middleware can be to listed or transferred at gin-contrib org? Please give me any advice and how to proceed? Thanks!
When I exit a call that has gone through the gzip middleware, I see it output junk data into the response body.
Cache-Control → private, max-age=30
Content-Encoding → gzip
Content-Length → 23
Content-Type → application/x-gzip
Date → Mon, 20 Apr 2015 12:23:56 GMT
Expires → Mon, 20 Apr 2015 09:24:26 GMT
Vary → Accept-Encoding
��� n�����
Hi, I have created an authorization middleware for Gin here: https://github.com/casbin/gin-authz
I saw the organization for plugins at: https://github.com/gin-contrib, And I want this plugin to be listed there, the authz
repo name would be good. But I don't have rights to create any repos there. Could you please tell me how to proceed? Thanks!
The ginrus example is currently broken. Logrus appears to have a new API (use Logger.Out = output
instead of Logger.SetOutput(output)
and there is an un-used import.
I needed to maintain URL rewriting from arbitrary path like "/help" to a path handled by router "/node/1234". Here is what I cam up with:
func UrlRewrite(ignore string) gin.HandlerFunc {
return func(c *gin.Context) {
if !strings.HasPrefix(c.Request.URL.Path, ignore) {
path := DecodeAlias(c.Request.URL.Path)
if path != c.Request.URL.Path {
c.Request.URL.Path = path
c.Engine.ServeHTTP(c.Writer, c.Request)
c.Abort(-1)
return
}
}
c.Next()
}
}
The DecodeAlias() above performs a lookup in URL alias table and returns either a decoded path or original one. The "ignore" parameter is to avoid decoding alias on static content. The idea here is to force router to restart handling with the decoded path, match to a different set of handlers, and process as necessary without sending redirect to the browser. The browser keeps seeing nice original URL. One may consider it a "server redirect."
Some of you may recognize Drupal URL aliasing method. So far this worked for me. I wonder if anyone has a better idea and whether it deserves to be added to contrib in some form.
Hi,
cannot use c (type *"gopkg.in/gin-gonic/gin.v1".Context) as type *"github.com/gin-gonic/gin".Context in argument to "github.com/gin-contrib/sessions".
Hi,
I was woking with the cors middleware (https://github.com/gin-contrib/cors) for 2 days, but today it seems the whole "gin-contrib" user, referenced many times in this repo, has gone.
Any clue? I'm not sure to understand the link between this repo and the gin-contrib user.
the travis build doesn't run anything - specifically, no unit tests.
some packages have testable examples though.
we should add automatic unit tests to the travis build.
When I used c.String for serving, gzip causes decoding error.
(Google Chrome said ERR_CONTENT_DECODING_FAILED. IE, Edge, Firefox also got same error.)
Even gzip/example/example.go did NOT worked, too. (My Golang version is 1.5)
In my project built under Golang 1.5, I tested several options like c.String, c.HTML, and c.JSON.
Result:
c.String(200, "OK") => Decoding Error
c.HTML(200, "blahblah.html", gin.H{"example": anything ~~~ ... }) => Gzip worked good
c.JSON(200, articles) => Gzip worked good
So, I think that there is a something issue with gzip + c.String.
I now need to delete session by doing like this.
session.Options(sessions.Options{MaxAge: -1})
session.Clear() // or whatever changes session.written to true
session.Save()
I think it would be better if
I'm sorry if I'm missing something.
Hi, first of all thanks for the awesome library. One of the things most people struggle when starting with gin (directly hopping from communities like rails, express, django) is templates and rendering.
From usability p.o.v, one of the things that struck me while using gin/multitemplate was, the following needs to be changed every time you add a new template or delete one of them. Which is not too handy and becomes repetitive to do in each handler when you are building a large application.
r.AddFromFiles("article", "base.html", "article.html")
r.AddFromFiles("login", "base.html", "login.html")
// ...
So based on multi template and the article I put some effort in enhancing the abilities. I would like to ask your opinion on it and decide if it can be used in multi template or make another package multitemplate-extras
or drop it.
Here's the gist https://gist.github.com/madhums/4340cbeb36871e227905 (It contains a readme and a .go file. It also contains link to a full demo, new comers may find it useful)
@manucorporat your feedback is highly appreciated. Thanks!
A middleware allowing for a signature mechanism similar to the AWS REST authentication could be quite useful.
Is there a way to limit the duration for a valid jwt token ?
commonlog Can you add request parameters and return data
Is this still maintained? if not can you add rights to merge pull requests and fix bugs?
@oryband I can see that the entry that is created here appends a time attribute:
https://github.com/gin-gonic/contrib/blob/master/ginrus/ginrus.go#L45
As far as I can see every log entry from logrus already has a time
key. Entry implements Stringer
, so the user could customise the timestamp in there.
https://github.com/sirupsen/logrus/blob/master/entry.go#L34-L35
As a consequence I end up having two time
attributes, one comes from logrus
and one from ginrus
. Any suggestion on how to tackle this? Should we overload the signature to allow a handler without that attribute to keep backwards compatibility?
Also, with the json encoder the label shows as fields.time
because of the duplicate entry from logrus...
comfuse issue when using gin-gonic /jwt-go middleware
running the example:
http://localhost:8080/api/ shows
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJRCI6IkNocmlzdG9waGVyIiwiZXhwIjoxNDMwMjMyMDMxfQ.T5ZM8Um_UPp7LNoRbs7cBT8R5BPN2jbkeCBu4SbQ2yM"}
and curl it:
curl -i http://localhost:8080/api/private/ -X GET --header "Authorization: BEARER
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJRCI6IkNocmlzdG9waGVyIiwiZXhwIjoxNDMwMjMyMDMxfQ.T5ZM8Um_UPp7LNoRbs7cBT8R5BPN2jbkeCBu4SbQ2yM"
Error #1: key is invalid or of invalid type
Meta: Operation aborted
seems the verify false.
what happend?
The bindata example is broken since the following commit
elazarl/go-bindata-assetfs@ed3050a#diff-0f54ed3f42051b1640ace89c556002fd
Error is as follows
Mikes-MBP:bindata mzupan$ go build && ./bindata
# _/Users/mzupan/contrib/static/example/bindata
./example.go:31: cannot use root (type string) as type func(string) (os.FileInfo, error) in field value
./example.go:31: too few values in struct initializer
Hello,
I'm currently working on Redis cache, wondering if it is possible to get the conn by some methods?
According to Redigos doc, it should be
pool.Get()
But since RedisStore.pool is kind of private, I don't see how to bypass it.
Any help?
Thanks.
The github path to logrus was recently changed from github.com/Sirupsen/logrus
to github.com/sirupsen/logrus
.
Packages have to adjust that otherwise they will no longer work with logrus: sirupsen/logrus#553
static middleware uses os.Stat which is not for Windows.
stats, err := os.Stat(name)
When trying to access urls the first request returns "hello world" for / which is expected.
However when revisiting the url the result body is empty and no hello world :-(
Tested with firefox, google chrome, cURL
Example code:
package main
import(
"github.com/gin-gonic/gin"
"github.com/gin-gonic/contrib/gzip"
)
func main() {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression))
r.GET("/", func(c *gin.Context) {
c.String(200, "hello world")
})
r.GET("/json", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "hello world"})
})
r.Run(":8080")
}
I am using the cache lib. I need to be able to delete the cache on command , rather than waiting for a TTL to expire.
Any ideas ?
`s := gin.New()
s.Use(gin.Recovery())
s.Use(gin.Logger())
store, _ := sessions.NewRedisStore(10, "tcp", "192.168.99.100:32775", "", []byte("secret"))
store.Options(sessions.Options{
MaxAge: 3600,
Path: "/",
Secure: true,
HttpOnly: true,
})
s.Use(sessions.Sessions("session", store))
s.GET("/home",controllers.Home)
`
controllers.Home
`
func Home(c *gin.Context) {
s := sessions.Default(c)
var count int
v := s.Get("count")
if v == nil {
count = 0
} else {
count = v.(int)
count += 1
}
s.Set("count", count)
s.Save()
c.JSON(200, gin.H{"count": count})
}`
/home return {"count":0} with no cookie
I have an Angular app to serve using Static middleware
, and AngularJS is a SPA framework, means it needs to catch all kinds of routes. My question is: can I do something like:
r.Use(static.Serve("/*", static.LocalFile("client/build", true)))
I attempted to use the multitemplate, but I get a type error when trying to
assign the multitemplate to router.HTMLRender
I am noticing that, when attempting to go get
the "static" middleware, I am presented with the following error in the console:
../../../../gin-gonic/contrib/static/static.go:86: not enough arguments in call to c.Abort
After some investigation, it appears that the GoDeps manifest is locking the gin version to a very old commit in which there was a single code argument required for the Abort method. See https://github.com/gin-gonic/gin/blob/c224bf82111883dbe354edf9376642f615b7248e/gin.go#L312
The current state of static.go seems to be written without the argument present (https://github.com/gin-gonic/contrib/blob/master/static/static.go#L86) which is correct according to the most recent commit to gin (https://github.com/gin-gonic/gin/blob/develop/context.go#L119).
Therefore, I am assuming that the GoDeps is out of date for some reason or that the "static" middleware was written against the develop branch... Please let me know if you would like a pull request on this issue. I can make one.
P.S. I am also noticing this same issue in the contrib/secure middleware code, but I will submit a separate issue for that one since they are different packages.
Session flashes aren't clearing I'm using go version go1.4.2 gccgo (GCC) 5.1.0 linux/amd64
There is only one "add flash" called and one "save" and then one "get flashes" and in Gorilla they're clearing, but they're not actually clearing on the next call. It removes them from the linked list but then a copy of gin somewhere must be taking over.
We will move https://github.com/gin-gonic/contrib all middlewares into into separate repos on gin-contrib org. The old single contrib repo is just for backward compatibility.
I have problem with in memory cache, when response is read from cache
it returns only:
</body>
</html>
Have you any idea what could be wrong?
I've configured my cache for handler like below:
app := gin.Default()
store := cache.NewInMemoryStore(time.Second)
app.GET("/", cache.CachePage(store, time.Minute, handler.Index))
(handler.Index is standard gin handler )
Change from martini-contrib/throttle
throttle
When visiting /static/
on a webserver that uses https://github.com/gin-gonic/contrib/blob/master/static/static.go to handle requests to /static/*
, I see a file listing. For security purposes, I would like to disable this.
Any thoughts on how to securely do this? Thanks!
/cc @ajvb
How about adding csrf token generation and middleware support to contrib, I notice there is this currently:
https://github.com/tommy351/gin-csrf
However, that requires tommmy351/gin-sessions rather than the sessions from gin-gonic/contrib/sessions, it would make sense to have a csrf library that worked with gin-gonic/contrib/sessions instead.
I also notice that gin-csrf seems to implement the csrf code from scratch, there is also gorilla/csrf that could have maybe been used as a foundation maybe? but gin-csrf does not appear to be using that.
I am getting this message error when I follow the example:
gpaes@cebola:~/gocode/src/heramodas.com.br/butik$ go run app.go
# github.com/gin-gonic/contrib/gzip
../../github.com/gin-gonic/contrib/gzip/gzip.go:29: c.Header undefined (type *gin.Context has no field or method Header)
../../github.com/gin-gonic/contrib/gzip/gzip.go:30: c.Header undefined (type *gin.Context has no field or method Header)
../../github.com/gin-gonic/contrib/gzip/gzip.go:33: c.Header undefined (type *gin.Context has no field or method Header)
gpaes@cebola:~/gocode/src/heramodas.com.br/butik$
I used reflect
to see what is exposed in c *gin.Context
and I did not find c.Header
. May be some gin update removed this function?
Is there any plan for a Boltdb-backed session store for the session package?
I have a struct eg:
type UserRow struct {
ID string
Name string
}
and a instance user eg:
u := NewUserRow()
when I use session.Set("user", user), it encounter a error:
securecookie: error - caused by: gob: type not registered for interface
how to fix it?
I know this is picky, but it screws up tooling for a large team.
It also breaks the newer censoring tools like gvt.
Any recommendations for how to force a pull ?
Go get -u -D ??
Here is a proposal to add as a contributed middleware for Gin.
https://gist.github.com/jamie-stackhouse/60c552446ea526385f31
The intention is to add support for checking four headers:
The middleware itself cannot know exactly what information is required for generating Etags, or Last-Modified dates for each route, so it follows an interface driven design.
Example Use:
route.GET("/", middleware.Conditional(cacheControl(models.PopulateVideosTime)), ctrl.retrieveVideos)
cacheControl
is a helper defined by the user to massage their functions which return their structs into returning the interface Cacher, and setting the required data for their Etag() or LastModified() functions to behave properly.
Included in the interface Cacher is a single method, SetId(string), this should be used to define any data required to successfully generate a Etag.
In our specific use-case this is a UUID, however, I could see a case for changing this to an interface{} value, and perhaps a more generic name.
Example cacheControl function
func cacheControl(method interface{}) func(c *gin.Context) middleware.Cacher {
return func(c *gin.Context) middleware.Cacher {
switch method.(type) {
case func(string) *models.Video:
constructor := method.(func(string) *models.Video)
resource := constructor(c.Params.ByName("network"))
resource.SetId(c.Params.ByName("id"))
return resource
case func(string) (models.Videos, error):
constructor := method.(func(string) (models.Videos, error))
resource, err := constructor(c.Params.ByName("network"))
if err != nil {
return nil
}
return resource
default:
c.Error(errors.New("No matching typecast for Cache middleware."), fmt.Sprintf(method))
return nil
}
}
}
Thoughts?
Suggestions?
Concerns?
I'm using the gzip middleware, but everytime i got an error status i got this error on chrome.
To solve it i changed the line 32 from:
c.Header("Content-Length", "")
to
c.Header("Content-Length", "0")
i think that maybe some browsers don't recognize the content-lenght's header without an int as value...
Is there any way to use templates from go-bindatas BinaryFileSystem instead of loading them from disk?
I'm trying to setup a cache store on redis, but I'm having some problems.
func main() {
r := gin.Default()
store := cache.NewRedisCache("localhost:6379", "", time.Second)
r.GET("/ping", cache.CachePage(store, time.Minute, func(c *gin.Context) {
c.String(http.StatusOK, "pong")
}))
r.Run(":8080")
}
When requesting /ping, GIN prints:
[GIN-debug] Listening and serving HTTP on :8080
2015/03/17 15:33:26 [GIN] WARNING. Headers were already written!
[GIN] 2015/03/17 - 15:33:26 | 500 | 3.964335ms | [::1]:50136 | GET /ping
Error #01: gob: type cache.responseCache has no exported fields
Meta: [pong []]
If I use the InMemoryCacheStore
it works.
I cannot see this option return back to preflight request. So it always says No 'Access-Control-Allow-Origin' header is present on the requested resource.
.
calls to c.Header under older api need to be updated
replace calls like
c.Header("Content-Encoding", "gzip")
with
c.Writer.Header().Set("Content-Encoding", "gzip")
I've tried using the exact example provided for gzip and found it does not work as intended.
This appears to be related to issue #35
Example in question: https://github.com/gin-gonic/contrib/blob/master/gzip/example/example.go
I get the following output:
curl -v -H "Accept-Encoding: gzip" 'http://localhost:8080/ping'
- Trying ::1...
- Connected to localhost (::1) port 8080 (#0)
GET /ping HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.43.0
Accept: /
Accept-Encoding: gzip< HTTP/1.1 200 OK
< Content-Encoding: gzip
< Content-Type: text/plain; charset=utf-8
< Vary: Accept-Encoding
< Date: Mon, 18 Jul 2016 17:20:56 GMT
< Content-Length: 38
<
- Connection #0 to host localhost left intact
pong 1468862456?n????
I'm not yet sure how to fix this. I assume the example code needs an update.
Thank you
Ciao,
It would be nice to have the possibility for the application to update itself with a zero downtime.
If i customize the options, like this
session := sessions.Default(c)
session.Options(sessions.Options{MaxAge: 60})
the cookie is lost
session := sessions.Default(c)
val := session.Get("user")
if val == nil ?
Using the "example.go" in JWT, and I'd like to know if there is a way to force token expiration
I'd like to use it when user logout, for example.
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.