Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 02:35
    togettoyou commented #2871
  • 02:32
    togettoyou opened #2872
  • 02:15
    togettoyou edited #2871
  • 02:06
    togettoyou commented #2871
  • 02:03
    togettoyou commented #2871
  • 02:02
    togettoyou commented #2871
  • 02:00
    togettoyou commented #2871
  • 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%
  • Sep 16 21:33
    codecov[bot] commented #2870
  • Sep 16 21:33
    Coverage (#2870) +0.00%
  • Sep 16 21:32
    codecov[bot] commented #2870
  • Sep 16 21:32
    Coverage (#2870) +0.00%
  • Sep 16 21:32
    codecov[bot] commented #2870
  • Sep 16 21:32
    Coverage (#2870) +0.00%
  • Sep 16 21:32
    codecov[bot] commented #2870
  • Sep 16 21:32
    Coverage (#2870) +0.00%
ahmar siddiqui
@ahhmarr
Hello good people 👋
is there any comprehensive guide that I can refer to regarding implementing testing in gin?
1 reply
Ghost
@ghost~5fbfef87d73408ce4ff5092d
hello
juemingzi
@gojuemingzi
world
simisimi
@iamatsundere
Hi team, I am new in Go. I have an issuse with authorization api resources and scope.
simisimi
@iamatsundere
For example, I have 2 apis (resources) like /users and /projects. /users has 2 subpath like /users/get and /users/delete, I just want to pre-check the permission of the access request, which comes with authorization info. For example, parsing the request and we got scope 'delete' and resource 'users', it can access /users/delete, but when access /users/get, it is denied. So my questtion is how can I define the scope and permission for endpoints in Go Gin? Thanks for reading!
1 reply
mahdi
@thisismz
Hello everyone
I have a question
I want to write a program that, for example, has a timekeeping function and We also have an infinite loop function to receive instant input from the user and print it
And also is very important to both work together
Do not wait for the first function to end
Mohammad Fayaz
@fayaz07
anyone running http2
Ryan W
@twentybit
Hi, is there an example of checking for mandatory request headers, and responding with a useful error back to the caller? I can easily catch this with ShouldBindHeader but I don’t get the reason as an err?
tyagip966
@tyagip966

Hello everyone,
I'm getting context cancelled error inside my go routine below is my code.

func (service maintenanceHandler) CardHandler(ctx *gin.Context) {
    var requestBody models.DefaultTicket

    //perform some action.

    go doSomethingElse(requestBody.Priority,ctx)
}

I also tried with

func (service maintenanceHandler) CardHandler(ctx *gin.Context) {
    var requestBody models.DefaultTicket

    //perform some action.

    go doSomethingElse(requestBody.Priority,ctx.Copy())
}

In both the case I'm getting CONTEXT CANCELLED inside go routine method, can anyone please help me in this?

Mohammad Fayaz
@fayaz07
Hi, how can I send the response and execute some code after sending the response to reduce response time
Stanisław Drozd
@drozdziak1
Hi, I'm trying to use BindJSON like this: https://paste.q3k.org/paste/wV2P1SdG#5gpfBdFCNygTgbmqRblICRZFbS5A7og5foV0uBdvuaz But my MessageDeleteQuery always becomes an empty struct and no error is caught
It fails only at req.code != msg.Code
ohhh, required, not requred :sweat:
Nah, that didn't change anything sadly
Stanisław Drozd
@drozdziak1
Got it, Needed to capitalize my field names
Antonino
@Antonin72982395_twitter
Hi to everybody! I'm implementig a web-app e I have a quetion! Is it possible to set a defaul value in a model?
Something like:
type MyModel struct {
key string `json:"key" bindind:"dafult=5"`
}
Antonino
@Antonin72982395_twitter
(sorry for my typos)
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.