Browse Source

update

mysql
evanchen333 8 months ago
parent
commit
fe8565ed5a
  1. 2
      Makefile
  2. 19
      example/main.go
  3. 8
      go.mod
  4. 11
      go.sum
  5. 59
      limiter.go

2
Makefile

@ -0,0 +1,2 @@
run:
go run example/main.go

19
example/main.go

@ -0,0 +1,19 @@
package main
import (
"fmt"
"net/http"
limiter "github.com/mutsuki333/rate-limiter"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
limiter.Default()
http.HandleFunc("/hit", handler)
http.ListenAndServe(":8080", nil)
}

8
go.mod

@ -0,0 +1,8 @@
module github.com/mutsuki333/rate-limiter
go 1.15
require (
github.com/mattn/go-sqlite3 v1.14.6
gorm.io/driver/sqlite v1.1.4
)

11
go.sum

@ -0,0 +1,11 @@
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
gorm.io/gorm v1.20.7 h1:rMS4CL3pNmYq1V5/X+nHHjh1Dx6dnf27+Cai5zabo+M=
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=

59
limiter.go

@ -0,0 +1,59 @@
package limiter
import (
"database/sql"
"time"
_ "github.com/mattn/go-sqlite3"
)
var ddb *sql.DB
func Default() *Limiter {
var err error
// ddb, err = sql.Open("sqlite3", "file::memory:?cache=shared")
ddb, err = sql.Open("sqlite3", "test.db")
if err != nil {
panic(err)
}
ddb.Exec(`create table hit (id integer, dt datetime);`)
return &Limiter{
Interval: time.Minute,
Limit: 60,
GetRate: getRate,
Hit: hit,
}
}
//Limiter the limiter instance
type Limiter struct {
//Interval the base of counting rate
Interval time.Duration
//Limit of counts within given interval
Limit int
GetRate func(time.Duration, string) (int, error)
Hit func(string) error
}
//Rate within interval
func (l *Limiter) Rate() int {
var rate int
return rate
}
//Exceeded the rate limit
func (l *Limiter) Exceeded() bool {
var exceed bool
return exceed
}
func getRate(i time.Duration, ip string) (rate int, err error) {
return
}
func hit(ip string) error {
return nil
}
Loading…
Cancel
Save