All Projects → vearne → gin-timeout

vearne / gin-timeout

Licence: MIT license
Timeout Middleware for Gin framework

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to gin-timeout

easy-gin
一套基于 Gin 框架的 MVC 脚手架,使用 govendor 包管理
Stars: ✭ 74 (+21.31%)
Mutual labels:  gin
short
URL shortening service. 高性能短链接服务。
Stars: ✭ 14 (-77.05%)
Mutual labels:  gin
go2sky-plugins
The plugins of go2sky
Stars: ✭ 46 (-24.59%)
Mutual labels:  gin
covid19-kerala-api-deprecated
Deprecated - A fast API service for retrieving day to day stats about Coronavirus(COVID-19, SARS-CoV-2) outbreak in Kerala(India).
Stars: ✭ 14 (-77.05%)
Mutual labels:  gin
popcat-echo
The server-side reproduction, similar the one of https://popcat.click, improve the performance and speed.
Stars: ✭ 62 (+1.64%)
Mutual labels:  gin
dlock
Interval Lock
Stars: ✭ 19 (-68.85%)
Mutual labels:  timeout
go-realworld-example-app
Exemplary real world application built with Go, Gin, and go-pg
Stars: ✭ 48 (-21.31%)
Mutual labels:  gin
ginprom
Gin Prometheus metrics exporter inspired by https://github.com/zsais/go-gin-prometheus
Stars: ✭ 97 (+59.02%)
Mutual labels:  gin
website
Official website and document for Gin
Stars: ✭ 88 (+44.26%)
Mutual labels:  gin
uot
🦁 A tiny setTimeout alternative with progress.
Stars: ✭ 43 (-29.51%)
Mutual labels:  timeout
go-gin-app
Fork from https://github.com/demo-apps/go-gin-app.git
Stars: ✭ 15 (-75.41%)
Mutual labels:  gin
hpay
a personal payment applet implemented using the gin framework
Stars: ✭ 71 (+16.39%)
Mutual labels:  gin
ipd
查询ip地理信息,多种查询模式,高效,具有缓存机制,并可使用elasticsearch构建自己的ip数据库
Stars: ✭ 24 (-60.66%)
Mutual labels:  gin
gapp
go gin应用
Stars: ✭ 42 (-31.15%)
Mutual labels:  gin
RetrofitHelper
💪 RetrofitHelper是一个支持配置多个BaseUrl,支持动态改变BaseUrl,动态配置超时时长的Retrofit帮助类
Stars: ✭ 15 (-75.41%)
Mutual labels:  timeout
blog
后端api采用go语言框架gin编写,前端使用vue + element ui编写
Stars: ✭ 45 (-26.23%)
Mutual labels:  gin
iam
企业级的 Go 语言实战项目:认证和授权系统
Stars: ✭ 1,900 (+3014.75%)
Mutual labels:  gin
iris-admin
Web admin for iris-go framwork
Stars: ✭ 602 (+886.89%)
Mutual labels:  gin
gin-gorm-api-example
[Article] Minimal code for Golang based API
Stars: ✭ 98 (+60.66%)
Mutual labels:  gin
geo-smart-system
Open Source Realtime Tracking System
Stars: ✭ 36 (-40.98%)
Mutual labels:  gin

gin-timeout

golang-ci

Timeout Middleware for Gin framework

Thanks

Inspired by golang source code http.TimeoutHandler

Usage

Download and install using go module:

export GO111MODULE=on
go get github.com/vearne/gin-timeout

Notice:

If the handler supports to be canceled,
you need to pass gin.Context.Request.Context() as parameter.

Example

more example

package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/vearne/gin-timeout"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func main() {
	// create new gin without any middleware
	engine := gin.Default()

	defaultMsg := `{"code": -1, "msg":"http: Handler timeout"}`
	// add timeout middleware with 2 second duration
	engine.Use(timeout.Timeout(
		timeout.WithTimeout(2*time.Second),
		timeout.WithErrorHttpCode(http.StatusRequestTimeout), // optional
		timeout.WithDefaultMsg(defaultMsg),                   // optional
		timeout.WithCallBack(func(r *http.Request) {
			fmt.Println("timeout happen, url:", r.URL.String())
		}))) // optional

	// create a handler that will last 1 seconds
	engine.GET("/short", short)

	// create a handler that will last 5 seconds
	engine.GET("/long", long)

	// create a handler that will last 5 seconds but can be canceled.
	engine.GET("/long2", long2)

	// create a handler that will last 20 seconds but can be canceled.
	engine.GET("/long3", long3)

	engine.GET("/boundary", boundary)

	// run the server
	log.Fatal(engine.Run(":8080"))
}

func short(c *gin.Context) {
	time.Sleep(1 * time.Second)
	c.JSON(http.StatusOK, gin.H{"hello": "short"})
}

func long(c *gin.Context) {
	time.Sleep(3 * time.Second)
	c.JSON(http.StatusOK, gin.H{"hello": "long"})
}

func boundary(c *gin.Context) {
	time.Sleep(2 * time.Second)
	c.JSON(http.StatusOK, gin.H{"hello": "boundary"})
}

func long2(c *gin.Context) {
	if doSomething(c.Request.Context()) {
		c.JSON(http.StatusOK, gin.H{"hello": "long2"})
	}
}

func long3(c *gin.Context) {
	// request a slow service
	// see  https://github.com/vearne/gin-timeout/blob/master/example/slow_service.go
	url := "http://localhost:8882/hello"
	// Notice:
	// Please use c.Request.Context(), the handler will be canceled where timeout event happen.
	req, _ := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, url, nil)
	client := http.Client{Timeout: 100 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		// Where timeout event happen, a error will be received.
		fmt.Println("error1:", err)
		return
	}
	defer resp.Body.Close()
	s, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("error2:", err)
		return
	}
	fmt.Println(s)
}

// A cancelCtx can be canceled.
// When canceled, it also cancels any children that implement canceler.
func doSomething(ctx context.Context) bool {
	select {
	case <-ctx.Done():
		fmt.Println("doSomething is canceled.")
		return false
	case <-time.After(5 * time.Second):
		fmt.Println("doSomething is done.")
		return true
	}
}

Thanks

jetbrains

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].