This is a collection of standard library modules for go i use in my projects. The package offers a set of modules that are useful in most projects such as logging,tracing,pooling,caching,HTTP Request,etc.
in code
import "github.com/karim-w/stdlib"
and
go get github.com/karim-w/stdlib
Caching tools are provided to make it easier to use caching in your projects. The package provides two types of caching, in memory and redis. The package uses the go-cache package for in memory caching and the go-redis package for redis caching.
uses the go-redis package
cache, err := InitRedisCache("redis://:@localhost:6379/0")
if err != nil {
t.Error(err)
}
err = cache.SetCtx(context.TODO(),"key",map[string]interface{}{
"value":8,
})
uses the go-cache package
cache, err := InitInMemoryCache(
time.Minute,
time.Minute*2,
)
if err != nil {
t.Error(err)
}
err = cache.SetCtx(context.TODO(),"key",map[string]interface{}{
"value":8,
})
use the ZapLogger or any other logger that implements the Logger interface
var logger *zap.Logger
newCache := cache.WithLogger(logger)
currently only support the applicationinsights tracer loacted at appinsights
var tracer *tracer.AppInsightsCore
newCache := cache.WithTracer(tracer)
The package provides a wrapper for the http package to make it easier to use. The package provides a client that can be used to make HTTP requests. The package also provides a middleware that can be used to add tracing and logging to the requests.
var logger *zap.Logger
client := stdlib.ClientProvider()
Note: This function WILL panic if it fails to initialize a logger
var logger *zap.Logger
var tracer *tracer.AppInsightsCore
client := stdlib.TracedClientProvider(
tracer,
logger,
)
type ClientOptions struct {
Authorization string //Authorization header
ContentType string //Content-Type header
Query string //Query string to append to the url
Headers *map[string]string //Headers to add to the request
Timeout *time.Time //Timeout for the request
}
The client provides 5 Main Methods to make requests which are GET
, POST
, PUT
, DELETE
, PATCH
. Each method takes a context, url, options, body and response. The response MUST be a pointer to the response type.
GET
And Del
do not take a body in the request.
Make a GET request
Response := interface{} //any type
code,err := client.Get(
context.TODO(),
"http://localhost:8080",
&stdlib.ClientOptions{},
&Response,
)
Note: MUST pass a pointer to the response
Make a POST request
Body := interface{} //any type
Response := interface{} //any type
code,err := client.Post(
context.TODO(),
"http://localhost:8080",
&stdlib.ClientOptions{},
Body,
&Response,
)
Note: MUST pass a pointer to the response
Make a PUT request
Body := interface{} //any type
Response := interface{} //any type
code,err := client.Put(
context.TODO(),
"http://localhost:8080",
&stdlib.ClientOptions{},
Body,
&Response,
)
Note: MUST pass a pointer to the response
Make a PATCH request
Body := interface{} //any type
Response := interface{} //any type
code,err := client.Patch(
context.TODO(),
"http://localhost:8080",
&stdlib.ClientOptions{},
Body,
&Response,
)
Note: MUST pass a pointer to the response
Make a DELETE request
Response := interface{} //any type
code,err := client.Del(
context.TODO(),
"http://localhost:8080",
&stdlib.ClientOptions{},
&Response,
)
Note: MUST pass a pointer to the response
client.SetAuthHandler(authProvider)
Auth provider must implement the AuthProvider
interface
type AuthProvider interface {
GetAuthHeader() string
}
The package provides a wrapper for the sql package to make it easier to use. The package provides a client that can be used to make SQL requests. The package also provides a middleware that can be used to add tracing and logging to the requests.
Only supports Postgres, planning to add more
Will not support MSSQL
db := stdlib.NativeDatabaseProvider(
databaseDriver,
databaseConnectionString,
)
for tracing and logging use the TracedNativeDBWrapper
function
db := stdlib.TracedNativeDBWrapper(
databaseDriver,
databaseConnectionString,
tracer,
dbName,
)
dbwithlogger := db.WithLogger(logger)
WARNING: Both functions will panic if they fail to initialize a logger
The client provides 3 Main Methods to make requests which are Query
, Exec
, QueryRow
. Each with a variant for context they all take in query, args.
Make a Query request that returns a single row
var res int
row := db.Query(
"SELECT COUNT(*) FROM table",
[]interface{}{}...,
)
err:=row.Scan(&res)
Make a Query request with context that returns a single row
var res int
row := db.QueryContext(
context.TODO(),
"SELECT COUNT(*) FROM table",
[]interface{}{}...,
)
err:=row.Scan(&res)
Execute a query that does not return a result rather the number of rows affected
res,err := db.Exec(
"INSERT INTO table VALUES($1,$2)",
[]interface{}{}...,
)
Execute a query that does not return a result rather the number of rows affected with context
res,err := db.ExecContext(
context.TODO(),
"INSERT INTO table VALUES($1,$2)",
[]interface{}{}...,
)
Make a Query request that returns multiple rows
res := []int{}
rows,err := db.Query(
"SELECT COUNT(*) FROM table",
[]interface{}{}...,
)
for rows.Next(){
var i int
err:=rows.Scan(&i)
if err!=nil{
return err
}
res = append(res,i)
}
Make a Query request with context that returns multiple rows
res := []int{}
rows,err := db.QueryContext(
context.TODO(),
"SELECT COUNT(*) FROM table",
[]interface{}{}...,
)
for rows.Next(){
var i int
err:=rows.Scan(&i)
if err!=nil{
return err
}
res = append(res,i)
}
Begin starts and returns a new transaction Object
tx,err := db.Begin()
Begin starts and returns a new transaction Object
tx,err := db.BeginTx(context.TODO(),opts) //opts is a *sql.TxOptions
newDb := db.withLogger(logger) //*zap.Logger
The package provides Pooling utility for any type of object. The package rotates the objects in the pool and provides a way to get the object from the pool in a round robin thread safe manner.
type customType struct{
//some fields
}
pool,err := stdlib.NewPooler(
func () *customType{
return &customType{}
},
&stdlib.PoolerOptions{
PoolSize: 10,
},
)
Get an object from the pool
obj := pool.Get()
Get the size of the pool
size := pool.Size()
Clear the pool
pool.Clear()