Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 12:28
    Ks89 edited #2875
  • 12:26
    Ks89 edited #2875
  • 12:26
    Ks89 opened #2875
  • 07:16
    helios741 commented #2873
  • 07:13
    helios741 opened #2874
  • 06:52

    appleboy on master

    chore: upgrade golangci to v1.4… (compare)

  • 06:50
    helios741 opened #2873
  • Sep 17 22:19
    FJM-Slade commented #454
  • Sep 17 02:35
    togettoyou commented #2871
  • Sep 17 02:32
    togettoyou opened #2872
  • Sep 17 02:15
    togettoyou edited #2871
  • Sep 17 02:06
    togettoyou commented #2871
  • Sep 17 02:03
    togettoyou commented #2871
  • Sep 17 02:02
    togettoyou commented #2871
  • Sep 17 02:00
    togettoyou commented #2871
  • Sep 17 01:24
    togettoyou opened #2871
  • Sep 16 21:34
    codecov[bot] commented #2870
  • Sep 16 21:34
    Coverage (#2870) +0.00%
  • Sep 16 21:34
    codecov[bot] commented #2870
  • Sep 16 21:34
    Coverage (#2870) +0.00%
Antonino
@Antonin72982395_twitter
And another question: how can I enable CORS ?
Sorry: I'm newbie! And thank to anyone'll answer
sk-cho
@sk-cho

How to use a type definition in another file with swaggo?
Using swaggo generate API document based on godoc syntax.
Source folder and files

    |-post
    |--controller.go
    |--response.go

For this definition:

    controller.go

    package post

    ...

    // Index godoc
    // @Summary Index Post
    // @Success 200 {array} []*Response
    // @Router /v1/posts [get]
    func Index(ctx *gin.Context) {
      ...
    }

The Response is been defined in an another file but the same package.

    response.go

    package post

    // Response  is post response body
    type Response struct {
        ID   int64  `json:"id"`
        Name string `json:"name"`

        CreatedAt string `json:"created_at"`
        UpdatedAt string `json:"updated_at"`
    }

But when run swag init to generate swagger docs, it said:

    2021/01/29 09:39:56 Generate swagger docs....
    2021/01/29 09:39:56 Generate general API Info, search dir:./
    2021/01/29 09:39:56 ParseComment error in file application/post/controller.go :cannot find type definition:

When I move the Response struct to controller.go, it works.
How to import it with godoc or swaggo?

sk-cho
@sk-cho
How to hide Models in gin-swagger?
mahdi
@thisismz
hello every one
I have just a simple question in python when we run this code:
( prefix_str = '0'*prefix_zeros )
we well get this result: '00000'
so my question is how we can do it in golang??
Mohammad Fayaz
@fayaz07

Hi @Antonin72982395_twitter , I don't think you can have default values just like that, but you can do something like below

func NewResponse(data interface{}) Response {
  // ... check nil and assign default values
}

or as an extension function

func (r *Response) SetDefaults() Response {
  // ... check nil and assign default values
}
Antonino
@Antonin72982395_twitter
hi @fayaz07 Thank you so much
Devin Ercolano
@devinercolano
Hi! One of my routes, /new-payment (this happens with all new routes) gets stuck on a redirect. My site goes from the URL http://localhost:8081/auth/new_payment_get to http://localhost:8081/new-payment, it’s missing /auth after the port and before the route (it should be redirected to http://localhost:8081/auth/new_payment_get). The POST route (http://localhost:8081/auth/new-payment) is supposed to be invoked when the user presses "submit" on a form on the "new_payment_get.html" page. Now it looks like http://localhost:8081/new_payment (it's supposed to be: http://localhost:8081/auth/new_payment_get.). The POST request registers on the server.
Huan Ran
@ranhuan
1
yiranzai
@yiranzai
gin-gonic/gin#2675 causes the engine.prepareTrustedCIDRS to never execute if gin is not started via gin.RUN().
Our project uses http.Handler to start the service instead of gin.Run
yiranzai
@yiranzai
yiranzai
@yiranzai
It is very urgent and I hope you can bring it to your attention
yiranzai
@yiranzai

gin-gonic/gin#2692
gin-gonic/gin#2693

When to deal with that?

Kevin Graham
@hongliu9527
I add a cors middleware to gin router
but the front request still been blocked
Sunil Joshi
@ersuniljoshi
spf13/viper
Sorry wrong winow
Romeo Mihalcea
@romeo.mihalcea:matrix.org
[m]
any ideas of a middleware that allows you to add a timeout per request? Except for this one which is bugged: https://github.com/gin-contrib/timeout
Shohan
@KIRA009
Has anyone ever tested websockets while using gin and gorilla websocket
Phillip Couto
@phillipCouto
@romeo.mihalcea:matrix.org I would look at context.Context and create a middleware that will reassign the c.Request.Context. The only way this works though is if all the code in your handlers are using the c.Request.Context so they cancel when the timeout occurs.
Maybe I can find time this week to create one if you have trouble.
coolder
@COOLMSF
I save session when login, but I can't get session when upload file.
Can anyone help?
The main function,
sess := r.Group("/", pkg.EnableCookieSession())
    {
        sess.POST("/login", post.Login)

        /*
         * Got problem here, session not working...
         */
        authorized := sess.Group("/auth", pkg.AuthSessionMiddle)
        // authorized := sess.Group("/auth")
        {
            authorized.POST("/upload", post.Upload)
            authorized.POST("/webshell", post.WebShell)
            authorized.StaticFS("/download", http.Dir("download"))
        }
    }
    err := r.Run(":3333")
    // err := r.RunTLS(":3333", "server.crt", "server.key")
    if err != nil {
        log.Fatal("r.Run")
    }
My Login function,
func Login(c *gin.Context) {
    tableName := "user_passwd"
    username := c.PostForm("username")
    password := c.PostForm("password")
    passwordMd5Form := fmt.Sprintf("%x", md5.Sum([]byte(password)))

    db, err := sql.Open("mysql", "root:hushanglai@tcp(localhost:3306)/web")
    if err != nil {
        log.Printf("sql.Open: %v", err)
    }
    defer func(db *sql.DB) {
        err := db.Close()
        if err != nil {
            log.Printf("Fail to close db:%v", err)
        }
    }(db)

    // Query password for a specified username
    sqlString := fmt.Sprintf("select password from %s where username=\"%s\"",
        tableName, username)

    res, err := db.Query(sqlString)
    defer func(res *sql.Rows) {
        err := res.Close()
        if err != nil {
            log.Printf("res.Close: %v", err)
        }
    }(res)
    if err != nil {
        log.Printf("db.Query: %v", err)
    }

    var passwordMd5Mysql string
    for res.Next() {
        err = res.Scan(&passwordMd5Mysql)
        if err != nil {
            c.String(http.StatusUnauthorized, "username or password wrong!")
        }
    }
    if passwordMd5Mysql != passwordMd5Form {
        c.String(http.StatusUnauthorized, "username or password wrong!")
        return
    }
    c.String(http.StatusOK, "Login successful")

    pkg.SaveAuthSession(c, username)
    c.JSON(http.StatusOK, gin.H{"message": "Successfully authenticated user"})
}
coolder
@COOLMSF
My pkg.SaveAuthSession,
func SaveAuthSession(c *gin.Context, username string) {
    session := sessions.Default(c)
    session.Set("user", username)
    err := session.Save()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save session"})
    }
    c.JSON(http.StatusOK, gin.H{"message": "save session ok"})
}

My pkg.AuthSessionMiddle function,

func AuthSessionMiddle(c *gin.Context) {
    session := sessions.Default(c)
    sessionValue := session.Get("user")
    if sessionValue == nil {
        c.JSON(http.StatusUnauthorized, gin.H{
            "error": "Unauthorized",
        })
        c.Abort()
        return
    }
    // c.Set("userId", sessionValue.(uint))
    c.Next()
    return
}

My problem is here, sessionValue := session.Get("user") won't get the session, I don't know why.

I am new to Go, can anyone help?
Thank you.
coolder
@COOLMSF
Sorry, my problem is here, session := sessions.Default(c) won't get the session that Login function saves.
coolder
@COOLMSF
I think sessions.Default(c) should return the session that Login() saves.
Phillip Couto
@phillipCouto
Where is the sessions suppose to be saved? In the cookie?
Steve McDaniel
@nibbleshift_gitlab
howdy
I am testing using the autotls with gin and I keep getting http: TLS handshake error from ... acme/autocert: missing server name
I am running with err = autotls.Run(r, "api.myvaliddomain.com")
I am not exactly sure what the issue is, but I am running my gin app inside of docker with ports 80 and 443 forwarded
Raphaël Yancey
@raphaelyancey_twitter
Hi :)
One of my Gin route handler starts a goroutine to handle the request in order to returns 200 asap (it's an event handler and the caller doesn't except any response).
I'm having a hard time testing that the goroutine is called, and testing what happens in it. Do you guys have any advice on the approach I should take?
Nikolay Kiselev
@kiselev-nikolay
Hi, are there any updates on new logo proposal gin-gonic/logo#6? This logo variant has more than 400 upvotes on reddit
Fabrizio Sestito
@fabriziosestito
Hi everyone, I'm struggling with gin not overriding a status code with a 500 if the error is caused from a method called in a template
Narsimham Chelluri
@narsimham_twitter
Hello, I have a question about data binding. Is it possible to normalize the data that comes out of the Bind functions? E.g. uppercase it, massage it, etc.
Rubi
@codenoid

Go Gin reCAPTCHA Example (v2 & v3)

https://github.com/codenoid/go-gin-recaptcha-example

Rubi
@codenoid
the forum is dead?
Pooja Yadav
@PoojaYa01281608_twitter
Hi everyone, Pooja here. I work as a Senior Marketing Coordinator at Packt. Looking at all the talk around Gin has encouraged me to share that Packt recently released a book on the framework. Building Distributed Applications in Gin: https://packt.link/niS8s by Mohamed Labouardy, do check the book and you can approach me if you'll like to have a free digital copy.
Bhagirath
@bhagirathgudi
@PoojaYa01281608_twitter I did like to have a free digital copy.
Pooja Yadav
@PoojaYa01281608_twitter
Sure, let's discuss in private.
Juan Pablo Tosso
@jptosso
Hey guys, I just integrated coraza-waf (A web application firewall) with Gin, I'm not a gin user so it's hard for me to write tests. I hope someone can check my project :) https://github.com/jptosso/coraza-gin
Yordis Prieto
@yordis

Hey folks, I am fairly new into Go, and Gin. I am trying to figure out how to do the following

// I need to do this
if validate, ok := binding.Validator.Engine().(*validator.Validate); ok {
            validate.RegisterTagNameFunc(jsonTagName)
        }

But I would like to do it at the router level

router := gin.New()
// can I do the binding validator thingy using `router` somehow?
Basically, how to remove that binding.Validator singleton setup