gin-gonic / examples Goto Github PK
View Code? Open in Web Editor NEWA repository to host examples and tutorials for Gin.
Home Page: https://gin-gonic.com/docs/
License: MIT License
A repository to host examples and tutorials for Gin.
Home Page: https://gin-gonic.com/docs/
License: MIT License
It would be very helpful if someone could post an example of how to return different format responses based on the Request Accept header.
I have searched for a long time and can not find any examples of how to actually render a response based on the Accept header.
And definitely not how to render based on a custom MediaType that has an API version number in it ("application/vnd.health.json;version=1.0.0") or ("application/vnd.kliket.health+v1.json", )
Here is what I have figured out so far:
func Health(c *gin.Context) {
startupTime := c.MustGet("startupTime").(time.Time)
status := models.NewHealth(startupTime)
c.Negotiate(http.StatusOK, gin.Negotiate{
Offered: []string{"application/vnd.health.json;version=1.0.0", gin.MIMEJSON, gin.MIMEYAML, gin.MIMEXML, gin.MIMEHTML},
HTMLName: "",
HTMLData: status,
JSONData: status,
XMLData: status,
YAMLData: status,
Data: status,
})
}
I can get back all the formats but HTML and my custom versioned MediaType which is the preferred one.
I can not find any example of what should go in HTMLName
or how to register a Render for my custom MediaType.
[GIN-debug] [ERROR] open ./testdata/server.pem: no such file or directory
as title, where can I get document about validate properties such as eqfield,nefield,gtefield etc...
type Booking struct { CheckIn time.Time
form:"check_in" binding:"required" time_format:"2006-01-02"CheckOut time.Time
form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02" }
hello, when a run the gin demo with websocket,it works.
but in my project, i have middlewares used to set token generate from jwt,and some permission verification .
when i use the demo, i find it doesn't work.
when i send a ws request, it seems that it didn't through the middleware i added.
Run the example, and the error occur
Key: 'BindFile.File' Error:Field validation for 'File' failed on the 'required' tag
The read.me in examples/app-engine/
seems need to be updated.
dev_appserver.py: error: too few arguments
In my case, varible A
were used in all of my html template, so is there some function to support global context for template rendering?
i have a problems when i try loggin del body because de body is null
gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
body, err := ioutil.ReadAll(param.Request.Body)
the problem is in my controller i have this code
var body entities.WriteChatRequest
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
the body was converted but now is null, when the controller finished and i try logging
Hi everyone, I wrote code for Hero template system example and
I merged it with Gin framework, i didn't see any like this in documentation, I think this can be useful for someone else.
I based my code en 2 basic examples.
I don't sure where post this, so I opened a issues
please feel free to write any suggestion.
@shiyanhui/hero
`package main
import (
"bytes"
"fmt"
"ginapp/template"
"io"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/someDataFromReader", func(c *gin.Context) {
var buffer bytes.Buffer
var reader io.Reader
contentType := "text/html , utf8"
extraHeaders := map[string]string{
"accept-ranges": "bytes",
}
var userList = []string{
"Alice",
"Bob",
"Tom",
}
template.UserList(userList, &buffer)
nRead := int64(len(buffer.Bytes()))
reader = bytes.NewReader(buffer.Bytes())
fmt.Println(nRead)
c.DataFromReader(http.StatusOK, nRead, contentType, reader, extraHeaders)
})
router.Run(":8080")
}
`
I just tried to get started with gin and I am struggling a bit with unit testing my sample app. Would it be possible to add a example with tests so that I can see how to properly test gin applications?
integrate with https://github.com/graphql-go/graphql
Add an example of how to use API versioning with Gin.
I am hoping someone has implemented OIDC Authentication in Gin-gonic, and maybe could share an example?
I am not sure if OIDC authentication would be considered middleware, so I am asking for "exaples" ;)
Maybe there would be some middleware that is just a thin wrapper around go-oidc?
Maybe just adapting some of the go-oidc examples ?
I have been trying to write this as middleware, but I am sort of lost at creating the routes/handlers from within middleware, which is why I am thinking maybe its a mix of example/middleware? I saw favicon "middleware" that looks like it parses every request to see if it is favicon.ico, then handles it, but that seems really inefficient. Can middleware inject routes to be handled by the regular router? (i.e. /auth/login and /auth/callback)
I am also not sure how the "state" would be maintained between the stages (See below)
I also have to assume that it would have to be combined with sessions to provide anything useful?
OIDC Auth (as I understand it)...
Stage 1:
Stage 2:
Stage 3:
So, We would have to have some way for the user to indicate they would like to login (or maybe they navigate to a URL that requires authentication, and the unauthorized page redirects them to login?). The login "handler" would have to "remember" where they were (maybe session can provide this?), and redirect the user to the authentication provider. I was also thinking a dynamic "Login" button could provide this, maybe in combination with the "location" middleware to parse out the return path? Additionally, some sort of "state" string is supposed to be passed to the auth provider (which will be returned) to prevent forged requests.
On redirect (after successful auth), the "callback" would have to "validate" the oidc token and the "state" string, then set the user's session with some useful information (like who they are). The OIDC examples just dump the details out on the screen, which I guess does prove that its working at the most basic level, but then the user probably wants to go visit the pages that require authentication, so it has to be attached to them somehow.
I was thinking that this is where the actual "middleware" would come in. The user could pass a token or "session_id" every time (cookie? or header maybe for API calls) that would be able to "revalidate" the JWT token from OIDC.
Thanks in advance!
Tommy
This link is dead
https://gin-gonic.com/docs/
router.UseH2C default is false
now http2 example not http2,it is http1.1
For Example:
can i add or remove middleware after gin server started dynamically? (after r.Run())
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
// Set example variable
c.Set("example", "12345")
// before request
c.Next()
// after request
latency := time.Since(t)
log.Print(latency)
// access the status we are sending
status := c.Writer.Status()
log.Println(status)
}
}
func main() {
r := gin.New()
r.Use(Logger())
r.GET("/test", func(c *gin.Context) {
example := c.MustGet("example").(string)
// it would print: "12345"
log.Println(example)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
}
Must I add this line of code here? Does it have any effect?
(Not sure if this is examples problem or gins problem. )
Hey,
The graceful shutdown example provided in examples/graceful-shutdown does not use gin.Run()
and instead calls the http.ListenAndServe()
directly.
It looks like gin.Run()
also does additional configurations on the engine before starting the server. These methods are private and implementing similar logic without copy/paste is not possible.
Problem: gin.Run()
does not expose the server instance anywhere to be able to call Shutdown()
on it.
Any ideas ?
I found this recipe in gqlgen repo, but I don't find a way in how to use GraphQL Dataload with Gin
I think the concurrent access to the map from multiple goroutines is not available.
What do you think?
The docs say that examples using next
should be present in this repo (https://pkg.go.dev/github.com/gin-gonic/gin#Context.Next). I'm a bit confused on the lifecycle of middleware. For example, say we have the following middleware:
func timerMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
t1 := time.Now()
c.Next()
t2 := time.Now().Sub(t1)
c.Header("time", t2.Seconds())
}
}
My goal here is to include the time it took to process the request as a response header. Is the above correct way of doing this?
Is there a simple way to update valid account map (username-password pairs) without killing the app, changing it in the code, recompiling it and running again? I'd love to see it in the example if it is possible!
There is the place where it is hardcoded.
How to Support WebSocket
For Example:
can i add or remove router after gin server started dynamically? (after r.Run())
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}
Hi, in the example Custom validators,
(
examples/custom-validation/server.go
Line 32 in 3a0d22a
v, ok := binding.Validator.Engine().(*validator.Validate)
returns v=nil and ok=false on my machine. Therefore the validator bookableDate
would not be registered.
Environment:
Windows 10
Go 1.13
github.com/gin-gonic/gin v1.5.0
github.com/go-playground/validator/v10 v10.2.0
Is it possible to add or enlarge an existing example so as to include custom error messages that should be returned to the consumer of the API we build?
I'm not able to add a custom validator and add as well a application specific defined message that is more descriptive than:
{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'required' tag"}%
Thanks!
Is there any MVC example, but not a single demo script?
Hi everybody.
I wanna install gin framework with below command,
go get -u github.com/gin-gonic/gin
but I got errors.
go: go.mod file not found in current directory or any parent directory.
'go get' is no longer supported outside a module.
To build and install a command, use 'go install' with a version,
like 'go install example.com/cmd@latest'
For more information, see https://golang.org/doc/go-get-install-deprecation
or run 'go help get' or 'go help install'.
Go is already installed and I was following steps of Gin doc.
What is solution?
see examples file upload
In actual projects, we usually have the need to upload large files
So we need to slice and transmit the file, and then splice and combine the files after transmission
Also, when the client fails to transmit, the breakpoint continues to transmit
Can you write these two commonly used functions into methods for developers to use? please...
Ubuntu 18.04.01 Server Edition
marco@pc01:~/go$ go version
go version go1.12.5 linux/amd64
marco@pc01:~/go/pkg/mod/github.com$ ls -lah
total 36K
drwxrwxr-x 9 marco marco 4.0K Jun 10 15:31 .
drwxrwxr-x 8 marco marco 4.0K May 31 08:40 ..
drwxrwxr-x 5 marco marco 4.0K Jun 10 15:08 gin-contrib
drwxrwxr-x 4 marco marco 4.0K Jun 10 15:08 gin-gonic
drwxrwxr-x 4 marco marco 4.0K Jun 10 15:08 golang
drwxrwxr-x 8 marco marco 4.0K May 31 08:40 gonum
drwxrwxr-x 5 marco marco 4.0K May 31 08:40 hashicorp
drwxrwxr-x 4 marco marco 4.0K Jun 10 15:08 mattn
drwxrwxr-x 3 marco marco 4.0K May 31 08:40 pbnjay
When trying to execute the multiple-services example:
marco@pc01:~/go/marcoGolang/gin-examples/multiple-service$ go run main.go
go: extracting github.com/ugorji/go v1.1.4
go: extracting github.com/ugorji/go/codec v0.0.0-20181209151446-772ced7fd4c2
build command-line-arguments: cannot load github.com/ugorji/go/codec: ambiguous import:
found github.com/ugorji/go/codec in multiple modules:
github.com/ugorji/go v1.1.4 (/home/marco/go/pkg/mod/github.com/ugorji/[email protected]/codec)
github.com/ugorji/go/codec v0.0.0-20181209151446-772ced7fd4c2 (/home/marco/go/pkg
/mod/github.com/ugorji/go/[email protected])
marco@pc01:~/go/marcoGolang/gin-examples/multiple-service$
marco@pc01:~/go/pkg/mod/github.com$ ls -lah;
total 40K
drwxrwxr-x 10 marco marco 4.0K Jun 10 15:32 .
drwxrwxr-x 8 marco marco 4.0K May 31 08:40 ..
drwxrwxr-x 5 marco marco 4.0K Jun 10 15:08 gin-contrib
drwxrwxr-x 4 marco marco 4.0K Jun 10 15:08 gin-gonic
drwxrwxr-x 4 marco marco 4.0K Jun 10 15:08 golang
drwxrwxr-x 8 marco marco 4.0K May 31 08:40 gonum
drwxrwxr-x 5 marco marco 4.0K May 31 08:40 hashicorp
drwxrwxr-x 4 marco marco 4.0K Jun 10 15:08 mattn
drwxrwxr-x 3 marco marco 4.0K May 31 08:40 pbnjay
drwxrwxr-x 4 marco marco 4.0K Jun 10 15:32 ugorji
marco@pc01:~/go/pkg/mod/github.com/ugorji$ ls -lah
total 16K
drwxrwxr-x 4 marco marco 4.0K Jun 10 15:32 .
drwxrwxr-x 10 marco marco 4.0K Jun 10 15:32 ..
drwxrwxr-x 3 marco marco 4.0K Jun 10 15:32 go
dr-x------ 3 marco marco 4.0K Jun 10 15:32 [email protected]
I realized that this happens for all examples.
How to solve the problem?
Can I implement more than one service and one api or should api be one for each service? I mean can gin api be one for 4 or 5 services ?
open ./testdata/server.pem: no such file or directory
@cp-sumi-k it appears that in your listen()
function you have a case to handle any incoming messages from a channel however, you also get data from that channel in the main()
function and send an SSEvent to it appears all clients listening to that endpoint - so is there any usage for the listen()
function at all?
Working with GIN for a while and looking for a solution with a CAS authentication mechanism.
Had a look to many gin-contrib, but found nothing relevant yet.
GO-CAS (https://github.com/go-cas/cas) seems fine, but struggling to put it in place with GIN.
Any example with GO-CAS (or any gin contrib pointer) would be appreciated.
Thx.
you can only use //go:embed for variables at the package level, not within functions or methods
2.go.mod must set go version is 1.16 or later
Hi, I don't know if this is due to updates in the gin gin framework since the SSEvent example has last been updated, but to actually make SSE work as intended I had to apply 2 changes to the example code:
a) after c.SSEvent()... a call to c.Writer.Flush() seems necessary, to get the event written out to the body writer, else it never sends the events out
b) to detect a client disconnect instead of listening to c.Done() listening to c.Request.Context().Done() works
If these points are necessary in general now, maybe the example code can be updated to include these minor changes?
type UpdateUserOperatorReq struct {
File *multipart.FileHeader `form:"file"`
UID *string `form:"uid" json:"uid"`
}
...
req := &UpdateUserOperatorReq{}
if err := c.ShouldBind(req); err != nil {
c.JSON(status, "")
return
}
logger(req.File)
// <nil>
I follow the example, but still getting nil. Please help fix this bug
As with #41, I'm trying to have Gin negotiate a custom mediatype. From the client, I'm sending the following request header:
Accept: application/problem+json, application/json
And on the server, I'm trying to negotiate all errors (with middleware) as such:
problem := Problem{
Detail: errorText,
Status: status,
Title: http.StatusText(status),
}
c.Negotiate(status, gin.Negotiate{
Offered: []string{"application/problem+json", gin.MIMEJSON, gin.MIMEHTML},
HTMLName: "error",
HTMLData: &problem,
JSONData: &problem,
})
However, somewhere before I'm able to handle the error, Gin intercepts and for some reason decides that the requested Accept
header can't be satisfied, writes the following to the log, and responds with 406 Not Acceptable
:
Error #01: the accepted formats are not offered by the server
I would love to see a full example of how content negotiation a custom mediatype in Gin works. Would you be able to contribute your working code @jarrodhroberson?
select {
case <-ctx.Done():
log.Println("timeout of 5 seconds.")
}
why is not under?
select {
case <-ctx.Done():
log.Println("timeout of 5 seconds.")
default:
}
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.