gkit

package module
v0.1.19 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 25, 2023 License: MIT Imports: 40 Imported by: 0

README

Gkit

Template for REST/GRPC API server made with Golang.

Features:

  • The log uses logrus
  • Load middleware cross-domain, add header
  • Graceful stop
  • Close connection to DB before stop
  • Response template error/success/success with pagination

Installation

To install gkit package, you need to install Go.

  1. You first need Go installed then you can use the below Go command to install gkit.
go get -u github.com/haoletesuji/gkit
  1. Import it in your code:
import "github.com/haoletesuji/gkit"

Quick start

Starting HTTP server

The example how to use gkit with to start REST api in example folder.

package main

import (
	"example/wire"
	"log"
)

func main() {
	server, err := wire.InitializeServer("gkit_example")
	if err != nil {
		log.Fatal(err)
	}
	server.Serve()
}

# run main.go and visit 0.0.0.0:3000/api/health on browser
$ go run main.go

Pre defination response template:

  • Error response: GET /api/error
type ErrResponse struct {
	Success bool   `json:"success" example:"false"`
	Error   string `json:"error"`
}
{
  "success": false,
  "error": "response error"
}
  • Successfull response: GET /api/success
type SuccessResponse[T any] struct {
	Success bool `json:"success" example:"true"`
	Data    T    `json:"data"`
}
{
  "success": true,
  "data": [
    {
      "uid": "1",
      "name": "John",
      "profile_image": "https://google.com/image/1"
    }
  ]
}
  • Successfull with pagination: GET /api/success_paging
type Pagination struct {
	Total int64 `json:"total"`
	Limit int64 `json:"limit"`
}

type SuccessPagingResponse[T any] struct {
	Success    bool       `json:"success" example:"true"`
	Data       T          `json:"data"`
	Pagination Pagination `json:"pagination"`
}
{
  "success": true,
  "data": [
    {
      "uid": "1",
      "name": "John",
      "profile_image": "https://google.com/image/1"
    }
  ],
  "pagination": {
    "total": 1,
    "limit": 10
  }
}
Starting GRPC server

The example how to use gkit with to start grpc server in example folder.

# run main.go
$ go run main.go

Then you will see the following logging

INFO[0000] grpc server listening on   0.0.0.0:50001      type=grpc

Using Postman to invoke functions Alt text

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidParam = errors.New("invalid parameter")
	ErrServer       = errors.New("server error")
	ErrUnauthorized = errors.New("unauthorized")
)
View Source
var (
	JWTAuthHeader = "Authorization"
	JaegerHeader  = "Trace-Id"
)
View Source
var (
	DefaultLimit int64 = 20
)
View Source
var (
	ServiceIdHeader string = "Service-Id"
)

Functions

func CheckPasswordHash added in v0.1.10

func CheckPasswordHash(password, hash string) bool

func ConstructKey

func ConstructKey(prefix, key string) string

func CorsMiddleware

func CorsMiddleware() gin.HandlerFunc

func ExtractToken added in v0.1.14

func ExtractToken(r *http.Request) string

func ExtractTokenFromHeader

func ExtractTokenFromHeader(r *http.Request) string

func GetEnv added in v0.1.4

func GetEnv(key, fallback string) string

func GetPageNumber

func GetPageNumber(page string) int

func GetServerAddrs

func GetServerAddrs(addrs string) []string

func HashPassword added in v0.1.10

func HashPassword(password string) (string, error)

func InitLogger

func InitLogger(mode string)

func InitializeGrpcClient added in v0.1.7

func InitializeGrpcClient(svcHost string) (*grpc.ClientConn, error)

func InitializeGrpcServer added in v0.1.7

func InitializeGrpcServer(logger GrpcLogger) *grpc.Server

func IsValidEmail added in v0.1.11

func IsValidEmail(email string) bool

func Join

func Join(strs ...string) string

func LogTraceUnary added in v0.1.7

func LogTraceUnary() grpc.UnaryServerInterceptor

LogTraceUnary logs trace id from the incoming request context

func LoggingMiddleware

func LoggingMiddleware(logger HttpLogger) gin.HandlerFunc

func MaxAllowed

func MaxAllowed(n int64) gin.HandlerFunc

func NewGrpcEndpoint added in v0.1.7

func NewGrpcEndpoint(conn *grpc.ClientConn, serviceID, serviceName, method string, grpcReply interface{}) endpoint.Endpoint

func ParseTimeYMD added in v0.1.12

func ParseTimeYMD(value string) *time.Time

func ResponseError added in v0.1.13

func ResponseError(c *gin.Context, httpCode int, err error)

func StringToStringValue added in v0.1.11

func StringToStringValue(value *string) *wrapperspb.StringValue

func StringValueToString added in v0.1.13

func StringValueToString(value *wrapperspb.StringValue) *string

func TimeToYMDStringValue added in v0.1.14

func TimeToYMDStringValue(t *time.Time) *wrapperspb.StringValue

func TokenAuthMiddleware added in v0.1.14

func TokenAuthMiddleware(secret string) gin.HandlerFunc

func TokenValid added in v0.1.14

func TokenValid(tokenString string, secret string) error

func VerifyToken added in v0.1.14

func VerifyToken(tokenString string, secret string) (*jwt.Token, error)

Types

type AccessDetails added in v0.1.15

type AccessDetails struct {
	AccessUuid string
	UserUuid   string
}

func ExtractRefreshTokenMetadata added in v0.1.16

func ExtractRefreshTokenMetadata(tokenString string, secret string) (AccessDetails, error)

func ExtractTokenMetadata added in v0.1.15

func ExtractTokenMetadata(tokenString string, secret string) (AccessDetails, error)

type Closer

type Closer interface {
	Close() error
}

type ErrResponse

type ErrResponse struct {
	Success bool   `json:"success" example:"false"`
	Error   string `json:"error"`
}

type GrpcLogger added in v0.1.7

type GrpcLogger struct {
	*log.Entry
}

func NewGrpcLogger added in v0.1.7

func NewGrpcLogger() GrpcLogger

type GrpcServer

type GrpcServer interface {
	Register()
	Run()
	GracefulShutdown()
}

type HttpLogger

type HttpLogger struct {
	*log.Entry
}

func NewHttpLogger

func NewHttpLogger() HttpLogger

type HttpServer

type HttpServer interface {
	RegisterRoutes()
	Run()
	GracefulShutdown(ctx context.Context) error
}

type IDGenerator

type IDGenerator interface {
	NextID() (uint64, error)
}

func NewIDGenerator

func NewIDGenerator() (IDGenerator, error)

type Migrator added in v0.1.5

type Migrator interface {
	Migrate() error
}

type Pagination

type Pagination struct {
	Total int64 `json:"total"`
	Limit int64 `json:"limit"`
}

type Runner

type Runner interface {
	Run()
	GracefulShutdown(ctx context.Context) error
}

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer(name string, runner Runner, closer Closer, migrator Migrator) *Server

func (*Server) GracefulShutdown

func (s *Server) GracefulShutdown(ctx context.Context, done chan bool)

func (*Server) Serve

func (s *Server) Serve()

type SuccessPagingResponse

type SuccessPagingResponse[T any] struct {
	Success    bool       `json:"success" example:"true"`
	Data       T          `json:"data"`
	Pagination Pagination `json:"pagination"`
}

type SuccessResponse

type SuccessResponse[T any] struct {
	Success bool `json:"success" example:"true"`
	Data    T    `json:"data"`
}

type TokenDetails added in v0.1.14

type TokenDetails struct {
	AccessToken  string
	RefreshToken string
	AccessUuid   string
	RefreshUuid  string
	AtExpires    int64
	RtExpires    int64
}

func CreateToken added in v0.1.14

func CreateToken(userUuid string, atSecret, rtSecret string, atExpires, rtExpires int64) (TokenDetails, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL