### Run the Form Binding Example Source: https://github.com/gin-gonic/examples/blob/master/form-binding/README.md Commands to navigate to the example directory and run the Go application. The server will start on http://localhost:8080. ```bash cd form-binding go run main.go ``` -------------------------------- ### Install Gin Dependencies Source: https://github.com/gin-gonic/examples/blob/master/graceful-shutdown/graceful-shutdown/README.md Use this command to install the necessary Gin framework dependencies before running the examples. ```bash go get -u github.com/gin-gonic/gin ``` -------------------------------- ### Install Dependencies Source: https://github.com/gin-gonic/examples/blob/master/new_relic/README.md Install the necessary Go module dependencies. ```sh go mod tidy ``` -------------------------------- ### Install Protocol Compiler Plugins Source: https://github.com/gin-gonic/examples/blob/master/grpc/example1/README.md Install the necessary protocol compiler plugins for Go. Ensure these are in your PATH. ```sh go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2 ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/gin-gonic/examples/blob/master/otel/README.md Clone the OTEL Gin example repository and navigate into the project directory. ```bash git clone https://github.com/your-repo/otel-gin-example.git cd otel-gin-example ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/gin-gonic/examples/blob/master/new_relic/README.md Clone the example repository and navigate to the new_relic directory. ```sh git clone https://github.com/your-repo/gin-examples.git cd gin-examples/new_relic ``` -------------------------------- ### Run the CORS Middleware Example Source: https://github.com/gin-gonic/examples/blob/master/cors-middleware/README.md Execute this command in your terminal to run the example application. ```bash go run main.go ``` -------------------------------- ### Run the Server Source: https://github.com/gin-gonic/examples/blob/master/graceful-shutdown/close/README.md Execute this command to start the Gin server. ```bash go run server.go ``` -------------------------------- ### Start Gin Server Source: https://github.com/gin-gonic/examples/blob/master/assets-in-binary/README.md Starts the Gin web server on the specified port. This should be the last call in the `main` function. ```go router.Run(":8080") ``` -------------------------------- ### Run Server - Shell Source: https://github.com/gin-gonic/examples/blob/master/websocket/README.md Execute the server Go program to start the WebSocket server. ```sh go run server/server.go ``` -------------------------------- ### Run gRPC Server Source: https://github.com/gin-gonic/examples/blob/master/grpc/example1/README.md Start the gRPC server application. This command executes the Go server file. ```sh go run grpc/server.go ``` -------------------------------- ### Run Notify with Context Server Source: https://github.com/gin-gonic/examples/blob/master/graceful-shutdown/graceful-shutdown/README.md Execute this command to start the Gin server that demonstrates graceful shutdown using context. ```bash go run notify-with-context/server.go ``` -------------------------------- ### Security Headers Example Source: https://github.com/gin-gonic/examples/blob/master/secure-web-app/README.md Demonstrates the security headers set by the Gin application. Use this to verify that all configured security headers are present and correctly formatted. ```http HTTP/1.1 404 Not Found Content-Security-Policy: default-src 'self'; connect-src *; font-src *; script-src-elem * 'unsafe-inline'; img-src * data:; style-src * 'unsafe-inline'; Content-Type: text/plain Permissions-Policy: geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=(),magnetometer=(),gyroscope=(),fullscreen=(self),payment=() Referrer-Policy: strict-origin Strict-Transport-Security: max-age=31536000; includeSubDomains; preload X-Content-Type-Options: nosniff X-Frame-Options: DENY X-Xss-Protection: 1; mode=block Date: Thu, 28 Mar 2024 11:38:05 GMT Content-Length: 18 ``` -------------------------------- ### Host Header Injection Example Source: https://github.com/gin-gonic/examples/blob/master/secure-web-app/README.md Simulates a Host Header Injection attempt. This example shows the expected 'Bad Request' response when an invalid Host header is provided, indicating the application's protection against SSRF. ```http HTTP/1.1 400 Bad Request Content-Type: application/json; charset=utf-8 Date: Thu, 28 Mar 2024 11:38:23 GMT Content-Length: 31 ``` -------------------------------- ### Run Gin Server Source: https://github.com/gin-gonic/examples/blob/master/grpc/example1/README.md Start the Gin web server, which likely interacts with the gRPC server. This command executes the main Go file for the Gin application. ```sh go run gin/main.go ``` -------------------------------- ### Gin Log Output Example Source: https://github.com/gin-gonic/examples/blob/master/ratelimiter/README.md Observe the Gin log output during the load test, showing the time taken for each request. ```bash [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 8.307734ms | 127.0.0.1 | GET /rate [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 10.512913ms | 127.0.0.1 | GET /rate [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 8.54681ms | 127.0.0.1 | GET /rate [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 8.356436ms | 127.0.0.1 | GET /rate [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 9.677276ms | 127.0.0.1 | GET /rate [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 7.536156ms | 127.0.0.1 | GET /rate [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 11.57084ms | 127.0.0.1 | GET /rate [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 7.802ms | 127.0.0.1 | GET /rate [GIN] 10ms [GIN] 2020/07/14 - 15:07:49 | 200 | 9.602394ms | 127.0.0.1 | GET /rate ``` -------------------------------- ### Example Application Output Source: https://github.com/gin-gonic/examples/blob/master/otel/README.md Observe the terminal output when the Gin application runs, including Gin's debug messages and OTEL trace information. ```bash [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) [GIN-debug] GET / --> main.main.func1 (4 handlers) [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value. Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details. [GIN-debug] Listening and serving HTTP on :8080 traceID: 00477d7b56b757d0581328ef21d17271; spanID: 9d05e83c0c188a16; isSampled: true [GIN] 2024/10/15 - 11:44:32 | 200 | 31.209µs | ::1 | GET "/" ``` -------------------------------- ### Start SSE Connection in JavaScript Source: https://github.com/gin-gonic/examples/blob/master/realtime-advanced/resources/room_login.templ.html This JavaScript function establishes an EventSource connection to the server for a given room ID and sets up event listeners for 'message' and 'stats' events. ```JavaScript function StartSSE(roomid) { var source = new EventSource('/stream/'+roomid); source.addEventListener('message', newChatMessage, false); source.addEventListener('stats', stats, false); } ``` -------------------------------- ### Run Notify without Context Server Source: https://github.com/gin-gonic/examples/blob/master/graceful-shutdown/graceful-shutdown/README.md Execute this command to start the Gin server that demonstrates graceful shutdown without explicit context, using a channel and server.Shutdown(). ```bash go run notify-without-context/server.go ``` -------------------------------- ### Update PATH for Protoc Source: https://github.com/gin-gonic/examples/blob/master/grpc/example1/README.md Update your system's PATH environment variable to include the Go binary directory, allowing the protoc compiler to find the installed plugins. ```sh export PATH="$PATH:$(go env GOPATH)/bin" ``` -------------------------------- ### Embed Static Files and Templates in Go Source: https://github.com/gin-gonic/examples/blob/master/assets-in-binary/README.md Use the `//go:embed` directive to embed files and directories into the Go binary. This example embeds files from the 'assets' and 'templates' directories. ```go //go:embed assets/* templates/* var f embed.FS ``` -------------------------------- ### Generate RSA Private Key with OpenSSL Source: https://github.com/gin-gonic/examples/blob/master/http2/README.md Use this command to generate a 2048-bit RSA private key. Ensure you have OpenSSL installed and a directory for test data. ```sh $ mkdir testdata $ openssl genrsa -out ./testdata/server.key 2048 ``` -------------------------------- ### Group Routes in Gin Gonic Source: https://github.com/gin-gonic/examples/blob/master/group-routes/README.md Organize routes into logical groups like API versions. This example shows creating groups for '/v1' and '/v2' and adding specific routes to each. ```go func getRoutes() { v1 := router.Group("/v1") addUserRoutes(v1) addPingRoutes(v1) v2 := router.Group("/v2") addPingRoutes(v2) } ``` -------------------------------- ### Send Form Data via cURL Source: https://github.com/gin-gonic/examples/blob/master/form-binding/README.md Example of sending a POST request to the /book endpoint with form data using cURL. Includes name, check-in, and check-out dates. ```bash curl -X POST http://localhost:8080/book \ -d "name=John Doe" \ -d "check_in=2025-06-21" \ -d "check_out=2025-06-25" ``` -------------------------------- ### Test Forward Proxy Request with Python Source: https://github.com/gin-gonic/examples/blob/master/forward-proxy/README.md Use this Python script to test the forward proxy functionality. Ensure the server is running and the 'forward=ok' header is set. The script sends a GET request to a target URL, utilizing the local proxy. ```python import requests def test_forward(): res=requests.get("http://www.baidu.com",headers={"forward":"ok"},proxies={"http":"http://127.0.0.1:8888"}) print (res.text) test_forward() ``` -------------------------------- ### Validation Error Response Source: https://github.com/gin-gonic/examples/blob/master/form-binding/README.md Example of a JSON response when validation fails due to a missing required field, such as 'name' or 'check_in'. ```json { "error": "Key: 'Booking.Name' Error:Field validation for 'Name' failed on the 'required' tag" } ``` -------------------------------- ### Example Requests for Struct Level Validations Source: https://github.com/gin-gonic/examples/blob/master/struct-lvl-validations/README.md These cURL commands demonstrate various scenarios for struct-level validations, including cases with missing required fields, cross-field validation failures, and successful validations when conditions are met. Observe the JSON output for validation errors and success messages. ```shell # Validation errors are generated for struct tags as well as at the struct level $ curl -s -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{}' | jq { "error": "Key: 'User.Email' Error:Field validation for 'Email' failed on the 'required' tag\nKey: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'fnameorlname' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'fnameorlname' tag", "message": "User validation failed!" } ``` ```shell # Validation fails at the struct level because neither first name nor last name are present $ curl -s -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{"email": "george@vandaley.com"}' | jq { "error": "Key: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'fnameorlname' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'fnameorlname' tag", "message": "User validation failed!" } ``` ```shell # No validation errors when either first name or last name is present $ curl -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{"fname": "George", "email": "george@vandaley.com"}' {"message":"User validation successful."} ``` ```shell $ curl -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{"lname": "Contanza", "email": "george@vandaley.com"}' {"message":"User validation successful."} ``` ```shell $ curl -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{"fname": "George", "lname": "Costanza", "email": "george@vandaley.com"}' {"message":"User validation successful."} ``` -------------------------------- ### Gin Application with New Relic Integration Source: https://github.com/gin-gonic/examples/blob/master/new_relic/README.md This Go code initializes a Gin router, configures the New Relic agent using environment variables, applies the New Relic middleware, and defines a simple "Hello World!" route. ```go package main import ( "log" "net/http" "github.com/gin-gonic/gin" "github.com/newrelic/go-agent/v3/integrations/nrgin" newrelic "github.com/newrelic/go-agent/v3/newrelic" ) func main() { router := gin.Default() app, err := newrelic.NewApplication( newrelic.ConfigAppName("MyApp"), newrelic.ConfigFromEnvironment(), ) if err != nil { log.Fatalf("failed to make new_relic app: %v", err) } router.Use(nrgin.Middleware(app)) router.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Hello World!\n") }) router.Run() } ``` -------------------------------- ### Run Tests for File Upload Scenarios Source: https://github.com/gin-gonic/examples/blob/master/upload-file/limit-bytes/README.md Execute the Go tests to verify the functionality of file uploads, including successful uploads, rejection of oversized files, and handling of missing files. ```bash go test ``` -------------------------------- ### Home Route Handler Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Handles the root path to display the home page with a link to initiate GitHub login. ```go r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{ "title": "GitHub OAuth Example", }) }) ``` -------------------------------- ### Configure Gin with Embedded Templates Source: https://github.com/gin-gonic/examples/blob/master/assets-in-binary/README.md Sets up a Gin web server and configures it to use embedded HTML templates. It parses templates from the embedded filesystem using `template.ParseFS`. ```go router := gin.Default() templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl")) router.SetHTMLTemplate(templ) ``` -------------------------------- ### OAuth2 Configuration Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Sets up the OAuth2 configuration with client credentials, redirect URL, and requested scopes for GitHub authentication. ```go var oauth2Config = oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, RedirectURL: redirectURL, Endpoint: github.Endpoint, Scopes: []string{"user:email", "read:user"}, } ``` -------------------------------- ### Run Client - Shell Source: https://github.com/gin-gonic/examples/blob/master/websocket/README.md Execute the client Go program in a separate terminal to connect to the WebSocket server. ```sh go run client/client.go ``` -------------------------------- ### Run Gin Server with Rate Limit Source: https://github.com/gin-gonic/examples/blob/master/ratelimiter/README.md Assign the ratelimit of the server by specifying requests per second (rps). ```go go run rate.go -rps=100 ``` -------------------------------- ### Test gRPC Service with grpcurl Source: https://github.com/gin-gonic/examples/blob/master/grpc/example1/README.md Interact directly with the gRPC service using the grpcurl tool. This command sends a SayHello request to the Greeter service. ```sh grpcurl -d '{"name": "gin"}' \ -plaintext localhost:50051 helloworld.v1.Greeter/SayHello ``` -------------------------------- ### Clone Repository Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Clone the project repository to your local machine. ```sh git clone https://github.com/yourusername/oidc.git cd oidc ``` -------------------------------- ### Set and Validate Cookies with Gin Source: https://github.com/gin-gonic/examples/blob/master/cookie/README.md This Go code sets up a Gin server with two routes: /login to set a cookie and /home to validate it using middleware. The cookie is set to expire in 30 seconds. ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func CookieTool() gin.HandlerFunc { return func(c *gin.Context) { // Get cookie if cookie, err := c.Cookie("label"); err == nil { if cookie == "ok" { c.Next() return } } // Cookie verification failed c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden with no cookie"}) c.Abort() } } func main() { route := gin.Default() route.GET("/login", func(c *gin.Context) { // Set cookie {"label": "ok" }, maxAge 30 seconds. c.SetCookie("label", "ok", 30, "/", "localhost", false, true) c.String(200, "Login success!") }) route.GET("/home", CookieTool(), func(c *gin.Context) { c.JSON(200, gin.H{"data": "Your home page"}) }) route.Run(":8080") } ``` -------------------------------- ### Clone Repository - Shell Source: https://github.com/gin-gonic/examples/blob/master/websocket/README.md Clone the project repository and navigate to the websocket directory. ```sh git clone https://github.com/your-repo/websocket-example.git cd websocket-example/websocket ``` -------------------------------- ### Serve Embedded Static Files with Gin Source: https://github.com/gin-gonic/examples/blob/master/assets-in-binary/README.md Configures Gin to serve static files from an embedded filesystem. The `http.FS` adapter is used to expose the embedded filesystem to Gin's `StaticFS` handler. ```go router.StaticFS("/public", http.FS(f)) ``` -------------------------------- ### Login Route Handler Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Handles the login path by generating a random state value, storing it, and redirecting the user to GitHub's authorization URL. ```go r.GET("/login", func(c *gin.Context) { state, err := generateRandomState() if err != nil { c.String(http.StatusInternalServerError, "Unable to generate state value") return } stateCache.Set(state, true, cache.DefaultExpiration) authURL := oauth2Config.AuthCodeURL(state) c.Redirect(http.StatusFound, authURL) }) ``` -------------------------------- ### Gin Server with Graceful Shutdown Source: https://github.com/gin-gonic/examples/blob/master/graceful-shutdown/close/README.md This Go code implements a Gin server that listens for interrupt signals to perform a graceful shutdown using `server.Close()`. It includes a route with a 5-second delay to test the shutdown process. ```go package main import ( "context" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() // Simulate a long-running request router.GET("/long_request", func(c *gin.Context) { log.Println("Received request for /long_request") time.Sleep(5 * time.Second) c.JSON(http.StatusOK, gin.H{ "message": "Request completed after 5 seconds", }) log.Println("Finished request for /long_request") }) server := &http.Server{ Addr: ":8080", Handler: router, } // Start the server in a goroutine go func() { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("listen: %s\n", err) } }() // Set up signal capturing stop := make(chan os.Signal, 1) ssignal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) // Wait for interrupt signal <-stop log.Println("Shutting down server...") // Create a context with a timeout for the shutdown ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Attempt graceful shutdown if err := server.Close(); err != nil { log.Fatal("Server forced to close:", err) } // Wait for all connections to close <-ctx.Done() log.Println("Server exiting") } ``` -------------------------------- ### Stream Room Events with Gin Source: https://github.com/gin-gonic/examples/blob/master/realtime-advanced/resources/room_login.templ.html This Go function streams SSE events for a specific room. It listens for messages and stats updates, sending them to the client. Requires 'gin' and 'time' packages. ```Go func streamRoom(c *gin.Context) { roomid := c.ParamValue("roomid") listener := openListener(roomid) statsTicker := time.NewTicker(1 * time.Second) defer closeListener(roomid, listener) defer statsTicker.Stop() c.Stream(func(w io.Writer) bool { select { case msg := <-listener: c.SSEvent("message", msg) case <-statsTicker.C: c.SSEvent("stats", Stats()) } return true }) } ``` -------------------------------- ### Set New Relic Environment Variables Source: https://github.com/gin-gonic/examples/blob/master/new_relic/README.md Configure your New Relic application name and license key using environment variables. ```sh export NEW_RELIC_APP_NAME="YourAppName" export NEW_RELIC_LICENSE_KEY="YourNewRelicLicenseKey" ``` -------------------------------- ### Encode SSE Events with manucorporat/sse Source: https://github.com/gin-gonic/examples/blob/master/realtime-advanced/resources/room_login.templ.html This Go code snippet demonstrates how to use the 'manucorporat/sse' package to encode and send SSE events. It supports both primitive data types and complex types like maps. ```Go import "github.com/manucorporat/sse" func httpHandler(w http.ResponseWriter, req *http.Request) { // data can be a primitive like a string, an integer or a float sse.Encode(w, sse.Event{ Event: "message", Data: "some data\nmore data", }) // also a complex type, like a map, a struct or a slice sse.Encode(w, sse.Event{ Id: "124", Event: "message", Data: map[string]any{ "user": "manu", "date": time.Now().Unix(), "content": "hi!", }, }) } ``` -------------------------------- ### Render Foo Page with Embedded Template Source: https://github.com/gin-gonic/examples/blob/master/assets-in-binary/README.md Defines a route for the 'Foo' page that renders an embedded HTML template. It uses `c.HTML` to render the `bar.tmpl` with a dynamic title. ```go router.GET("/foo", func(c *gin.Context) { c.HTML(http.StatusOK, "bar.tmpl", gin.H{ "title": "Foo website", }) }) ``` -------------------------------- ### Upload a Valid File (within 1MB) Source: https://github.com/gin-gonic/examples/blob/master/upload-file/limit-bytes/README.md Use cURL to upload a file that is within the defined size limit. Expects a success message. ```bash curl -F "file=@smallfile.bin" http://localhost:8080/upload # Response: {"message":"upload successful"} ``` -------------------------------- ### Define Booking Struct with Form Tags Source: https://github.com/gin-gonic/examples/blob/master/form-binding/README.md Defines a Go struct for booking information, using form tags to map request fields and binding tags for validation. Includes custom time format parsing. ```go type Booking struct { Name string `form:"name" binding:"required" CheckIn *time.Time `form:"check_in" time_format:"2006-01-02" binding:"required" CheckOut *time.Time `form:"check_out" time_format:"2006-01-02" } ``` -------------------------------- ### Serve Embedded Favicon Source: https://github.com/gin-gonic/examples/blob/master/assets-in-binary/README.md Handles requests for the favicon by reading the file directly from the embedded filesystem and serving it with the correct MIME type. ```go router.GET("favicon.ico", func(c *gin.Context) { file, _ := f.ReadFile("assets/favicon.ico") c.Data( http.StatusOK, "image/x-icon", file, ) }) ``` -------------------------------- ### Load Test Gin Server with AB Source: https://github.com/gin-gonic/examples/blob/master/ratelimiter/README.md Perform a load test using `ab` with 3000 mock requests and a concurrency level of 1 to test the rate limiting. ```bash ab -n 3000 -c 1 http://localhost:8080/rate ``` -------------------------------- ### AB Test Reporter Summary Source: https://github.com/gin-gonic/examples/blob/master/ratelimiter/README.md View the summary report from the `ab` load test, indicating the requests per second and time per request. ```text Concurrency Level: 1 Time taken for tests: 30.00 seconds Complete requests: 3000 Requests per second: 100.00 [#/sec] (mean) Time per request: 10.001 [ms] (mean) Time per request: 10.001 [ms] (mean, across all concurrent requests) ``` -------------------------------- ### Render Homepage with Embedded Template Source: https://github.com/gin-gonic/examples/blob/master/assets-in-binary/README.md Defines a route for the homepage that renders an embedded HTML template. It uses `c.HTML` to render the `index.tmpl` with a dynamic title. ```go router.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "title": "Main website", }) }) ``` -------------------------------- ### Set Environment Variables Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Configure GitHub OAuth2 application credentials as environment variables. ```sh export GITHUB_CLIENT_ID=your_github_client_id export GITHUB_CLIENT_SECRET=your_github_client_secret ``` -------------------------------- ### Callback Route Handler Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Handles the callback from GitHub after authentication. It verifies the state, exchanges the authorization code for an access token, retrieves user information, and renders a success page. ```go r.GET("/callback", func(c *gin.Context) { state := c.Query("state") if _, exists := stateCache.Get(state); !exists { c.String(http.StatusBadRequest, "Invalid state value") return } stateCache.Delete(state) code := c.Query("code") if code == "" { c.String(http.StatusBadRequest, "Authorization code not provided") return } token, err := oauth2Config.Exchange(context.Background(), code) if err != nil { c.String(http.StatusInternalServerError, "Unable to exchange access token: "+err.Error()) return } client := oauth2Config.Client(context.Background(), token) resp, err := client.Get(userInfoURL) if err != nil { c.String(http.StatusInternalServerError, "Unable to retrieve user information: "+err.Error()) return } defer resp.Body.Close() var user GitHubUser if err := json.NewDecoder(resp.Body).Decode(&user); err != nil { c.String(http.StatusInternalServerError, "Unable to parse user information: "+err.Error()) return } c.HTML(http.StatusOK, "success.html", gin.H{ "title": "Authentication Successful", "username": user.Login, "name": user.Name, "email": user.Email, "avatar_url": user.AvatarURL, }) }) ``` -------------------------------- ### Listen to SSE Stream in JavaScript Source: https://github.com/gin-gonic/examples/blob/master/server-sent-event/public/index.html Use the EventSource API to connect to a server stream and handle incoming messages. Append received data to an HTML element with the class 'event-data'. ```javascript var stream = new EventSource("/stream"); stream.addEventListener("message", function(e){ $(".event-data").append(e.data + "
") }); ``` -------------------------------- ### Regenerate gRPC Code Source: https://github.com/gin-gonic/examples/blob/master/grpc/example1/README.md Generate Go code for gRPC services from a .proto file. This command uses protoc with specific output options for Go and gRPC. ```sh protoc --go_out=gen --go_opt=paths=source_relative \ --go-grpc_out=gen --go-grpc_opt=paths=source_relative \ -I=$PWD pb/helloworld.proto ``` -------------------------------- ### Generate Digital Certificate with OpenSSL Source: https://github.com/gin-gonic/examples/blob/master/http2/README.md This command creates a self-signed digital certificate valid for 365 days, using the previously generated private key. This is useful for local development and testing. ```sh $ openssl req -new -x509 -key ./testdata/server.key -out ./testdata/server.pem -days 365 ``` -------------------------------- ### Protected Route Handler Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Defines a protected route that requires authentication. Accessing this route will return a success message. ```go r.GET("/protected", func(c *gin.Context) { c.String(http.StatusOK, "This is a protected resource!") }) ``` -------------------------------- ### GitHub User Struct Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Defines the structure for unmarshaling user information received from the GitHub API. ```go type GitHubUser struct { ID int `json:"id"` Login string `json:"login"` Name string `json:"name"` Email string `json:"email"` AvatarURL string `json:"avatar_url"` } ``` -------------------------------- ### Test Gin Server with cURL Source: https://github.com/gin-gonic/examples/blob/master/grpc/example1/README.md Send a request to the Gin server's REST endpoint using cURL. This is useful for testing the integration between Gin and gRPC. ```sh curl -v 'http://localhost:8080/rest/n/gin' ``` -------------------------------- ### Handle Missing File Upload Source: https://github.com/gin-gonic/examples/blob/master/upload-file/limit-bytes/README.md When no file is provided in the upload request, the server returns a 400 status code with a specific error message. ```json {"error":"file form required"} ``` -------------------------------- ### Upload an Oversized File (e.g., 2MB) Source: https://github.com/gin-gonic/examples/blob/master/upload-file/limit-bytes/README.md Use cURL to upload a file exceeding the size limit. Expects a custom JSON error response with status 413. ```bash curl -F "file=@bigfile.bin" http://localhost:8080/upload # Response: {"error":"file too large (max: 1048576 bytes)"} ``` -------------------------------- ### Handle File Too Large Error Source: https://github.com/gin-gonic/examples/blob/master/upload-file/limit-bytes/README.md When a file exceeds the maximum allowed size, the server returns a 413 status code with a custom error message indicating the limit. ```json {"error":"file too large (max: 1048576 bytes)"} ``` -------------------------------- ### Successful JSON Response Source: https://github.com/gin-gonic/examples/blob/master/form-binding/README.md The expected JSON response when form data is successfully bound and validated. Includes the parsed name and dates. ```json { "name": "John Doe", "check_in": "2025-06-21T00:00:00Z", "check_out": "2025-06-25T00:00:00Z" } ``` -------------------------------- ### Generate Random State Function Source: https://github.com/gin-gonic/examples/blob/master/oidc/README.md Generates a cryptographically secure random string to be used as the state parameter in OAuth2 requests, helping to prevent CSRF attacks. ```go func generateRandomState() (string, error) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { return "", err } return base64.URLEncoding.EncodeToString(b), nil } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.