Giter Site home page Giter Site logo

gin-gonic / examples Goto Github PK

View Code? Open in Web Editor NEW
3.5K 47.0 624.0 540 KB

A repository to host examples and tutorials for Gin.

Home Page: https://gin-gonic.com/docs/

License: MIT License

Go 74.95% JavaScript 5.47% Makefile 0.79% HTML 18.79%
gin gin-gonic go

examples's People

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

examples's Issues

How can I install Gin framework?

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?

Update accounts in Basic Auth example

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.

Content negotiate custom mediatype

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?

How about an example with GO-CAS ?

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.

support for websocket middleware

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.

Graceful shutdown example outdated

(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 ?

Hero Template Example

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

}
`

File Binding Not Working!

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

file-upload requires fragment upload and breakpoint continuation

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

More than one service

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 ?

SSEvent example, possible redundancy

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

How can i generate assets.go???

image

How can I do right now? I could not use command go-assets-builder html -o assets.go
And the result is always zsh: command not found: go-assets-builder
Please help me...

Might be a bug in the example custom-validation

Hi, in the example Custom validators,
(

if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
)
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

How can i add or remove middleware after gin server started dynamically?

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

hi , where can I get explanation about "binding:"gtfield=CheckIn"

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.Timeform:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02" }

file-binding error

Run the example, and the error occur

Key: 'BindFile.File' Error:Field validation for 'File' failed on the 'required' tag

Expand custom error messages to include API specific errors

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!

Add tests

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?

file is exist!!

[GIN-debug] [ERROR] open ./testdata/server.pem: no such file or directory

cannot load github.com/ugorji/go/codec: ambiguous import: found github.com/ugorji/go/codec in multiple modules

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?

body is null in LoggerWithFormatter

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

How can i add or remove router after gin server started dynamically?

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 上启动服务
}

OIDC Authentication example? (GitHub, Google, etc)

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:

  • When the user wishes to login, this webserver will send them a redirect to an authentication provider (IdP), like accounts.google.com or github or whatever.

Stage 2:

  • Assuming the user successfully authenticates to the authentication provider, it will redirect them back to the application with a token that the go-oidc code can "validate" ... thus proving the user's "identity"

Stage 3:

  • Allow the user to "logout" to end their authenticated session.

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

context.Next()

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?

SSEvent example small changes to make it work

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?

Idiomatic example of how to use Context.Negotiate with generic and custom MediaTypes

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.

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.