Giter VIP home page Giter VIP logo

examples's Introduction

Gin Examples

This repository contains a number of ready-to-run examples demonstrating various use cases of Gin.

Refer to the Gin documentation for how to execute the example tutorials.

Contributing

Are you missing an example? Please feel free to open an issue or commit one pull request.

Please see CONTRIBUTING.md for instructions on how to contribute.

examples's People

Contributors

4k1k0 avatar appleboy avatar borisborshevsky avatar boynchan avatar cp-sumi-k avatar d4nyll avatar dmlambea avatar easonlin404 avatar firstrow avatar ganlvtech avatar glonee avatar javierprovecho avatar jbampton avatar jeremyloy avatar jodezer avatar kelein avatar kristoiv avatar manucorporat avatar mosdeo avatar ngerakines avatar panmax avatar r723235 avatar r8k avatar rbeuque74 avatar sudo-suhas avatar thinkerou avatar verymiao avatar wgdzlh avatar wybcp avatar zignd 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  avatar  avatar  avatar  avatar

examples's Issues

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 ?

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.

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.

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?

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

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

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

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?

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

}
`

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

Ubuntu 18.04.01 Server Edition

[email protected]:~/go$ go version
go version go1.12.5 linux/amd64


[email protected]:~/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:

[email protected]:~/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])
[email protected]:~/go/marcoGolang/gin-examples/multiple-service$ 

[email protected]:~/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

[email protected]:~/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?

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

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 ?

file-binding error

Run the example, and the error occur

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

file is exist!!

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

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?

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!

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

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.

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

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.