Coder Social home page Coder Social logo

contrib's People

Contributors

andreynering avatar appleboy avatar aviddiviner avatar avignat avatar bluele avatar bu avatar danielkov avatar darh avatar dieselburner avatar ekyoung avatar fatihkahveci avatar fdelbos avatar iceyer avatar janekolszak avatar javierprovecho avatar jbampton avatar kimiazhu avatar kubastick avatar llinder avatar lyrictian avatar manucorporat avatar mcastilho avatar mirzac avatar mopemope avatar paskal avatar sashamelentyev avatar shawnzhu avatar teutonicjoe avatar thinkerou avatar utrack 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

contrib's Issues

Add ability to delete session forcibly

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

  • DeleteSession() method is added

    or
  • Save() method takes a parameter to save session regardless of the session.written flag

I'm sorry if I'm missing something.

enhancing multi template and rendering

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!

Url alias middleware

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.

gzip: c.Header is not exposed

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?

gzip causes ERR_CONTENT_DECODING_FAILED with c.String

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.

gzip returning junk data with empty response body

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�����

gzip middleware net::ERR_INVALID_RESPONSE

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...

Redis cache store

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.

Use `session.Set` encounter a error

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?

static middleware will not compile - c.Abort does not contain the proper number of arguments

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.

InMemoryStore cut off response

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 )

Redis session store ,Options not working

    `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

ginrus example broken

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.

Any plans on a csrf middleware?

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.

Gzip middleware - Revisiting urls gives empty response body

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")
}

gzip example not working

@javierprovecho
@manucorporat

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

session flashes not clearing

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.

Add Conditional Request Support

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:

  • If-None-Match
  • If-Match
  • If-Modified-Since
  • If-Unmodified-Since

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?

JWT force token expiration

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

Package dependencies

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".

[WIP] Move all middleware into separate repos on gin-contrib org

auto update

Ciao,

It would be nice to have the possibility for the application to update itself with a zero downtime.

Still maintained?

Is this still maintained? if not can you add rights to merge pull requests and fix bugs?

session Options is not working

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 ?

jwt-go example false..

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?

commonlog

commonlog Can you add request parameters and return data

`time` attribute duplicated in logrus/ginrus entry

@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...

error in multitemplate

I attempted to use the multitemplate, but I get a type error when trying to
assign the multitemplate to router.HTMLRender

Catch all route with static middleware

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)))

Get Redis Conn?

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.

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.