This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

introduce

With a complete example, implement timeout middleware in a microservice based on Gin framework.

We will use RK-boot to start the Gin framework microservice.

Please visit the following address for the full tutorial:

  • rkdocs.netlify.app/cn

The installation

go get github.com/rookie-ninja/rk-boot
Copy the code

Quick start

Supports global timeout and API timeout Settings.

1. Create the boot. Yaml

The boot.yaml file tells RK-boot how to start the Gin service.

To verify, we enabled the following options:

  • CommonService: commonService contains a set of common apis. details

Set the global timeout to 5 seconds and make the GC timeout to 1 millisecond, which GC usually exceeds.

---
gin:
  - name: greeter                                   # Required
    port: 8080                                      # Required
    enabled: true                                   # Required
    commonService:
      enabled: true                                 # Optional, Enable common service for testing
    interceptors:
      timeout:
        enabled: true                               # Optional, default: false
        timeoutMs: 5000                             # Optional, default: 5000
        paths: 
          - path: "/rk/v1/gc"                       # Optional, default: ""
            timeoutMs: 1                            # Optional, default: 5000
Copy the code

2. Create a main. Go

// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package main

import (
	"context"
	"github.com/rookie-ninja/rk-boot"
)

// Application entrance.
func main(a) {
	// Create a new boot instance.
	boot := rkboot.NewBoot()

	// Bootstrap
	boot.Bootstrap(context.Background())

	// Wait for shutdown sig
	boot.WaitForShutdownSig(context.Background())
}
Copy the code

3. Start the main. Go

$ go run main.go
Copy the code

4. Verify

Send the GC request.

$ curl -X GET localhost:8080/rk/v1/gc { "error":{ "code":408, "status":"Request Timeout", "message":"Request timed out!" , "details":[] } }Copy the code