crema

package module
v0.0.0-...-469fe9d Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2020 License: MIT Imports: 15 Imported by: 0

README

Crema

Crema is a Simple Go-Based RESTful API Framework originally written by Universitas Pertamina ICT teams to support its Microservices environment development. It is written in pure Go and completely free. Crema is now maintained by a small independent research and development team, and is also supported by Hexavara Foundation.

RESTful

Playing with RESTful API using Crema is fun and easy

  • Create HTTP routes
func main() {
	server := crema.InitServer()

	server.AddRoutes(http.MethodGet, "/hello", hello)
	server.AddRoutes(http.MethodGet, "/users", crema.MakeGenericGetHandler(getUser))
  
	crema.LogPrintf("[MAIN] Server is running, listening to port 8001 ....")

	log.Fatal(http.ListenAndServe(":8001", server.Router))
}
  • Create Handlers
func hello(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World!"))
}

func getUser(conditions map[string]string) (*sql.Rows, error) {
	q := crema.Select().All().From("users")

	return crema.ExecuteQuery(q.QueryString)
}
  • Try it using cURL
$ curl http://localhost:8001/hello
Hello World!

$ curl http://localhost:8001/users
{"status":1,"message":"Success 200","data":[{"email":"john.doe@email.com","id":16,"name":"John Doe"},{"email":"bob@email.com","id":17,"name":"Bob"}]}

What's Inside

  • A Gorilla Mux-based HTTP router
  • Customizable generic request handler
  • Simplified Data Access Object mechanism
  • PostgreSQL and MySQL database driver
  • Personalized system logger

Installation

  1. With a correctly configured Go toolchain:
$ go get github.com/gadp22/crema
  1. Import in your code
import "github.com/gadp22/crema"

Examples and Tutorials

How to set up your first project using Crema.

See here to see basic example to build a CRUD API.

See here to see further documentations.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Data map[string]interface{}

Functions

func BeginTransaction

func BeginTransaction() (*sql.Tx, error)

func DeleteData

func DeleteData(fn func(*sql.Tx, map[string]string) (sql.Result, error), w http.ResponseWriter, r *http.Request) (interface{}, int)

DeleteData performs the standard delete mechanism TO DO : documentaion will be updated soon

func DeleteUser

func DeleteUser(tx *sql.Tx, conditions map[string]string) (sql.Result, error)

func ExecuteNonQuery

func ExecuteNonQuery(queryString string) (sql.Result, error)

func ExecuteNonQueryTransaction

func ExecuteNonQueryTransaction(tx *sql.Tx, queryString string) (sql.Result, error)

func ExecuteQuery

func ExecuteQuery(queryString string) (*sql.Rows, error)

func ExecuteQueryRow

func ExecuteQueryRow(tx *sql.Tx, queryString string) *sql.Row

func GenerateJWT

func GenerateJWT(data interface{}, expiration time.Duration) (string, error)

GenerateJWT generates new JWT token TO DO : documentaion will be updated soon

func GetData

func GetData(fn func(map[string]string) (*sql.Rows, error), w http.ResponseWriter, r *http.Request) (interface{}, int)

GetData performs the standard get mechanism TO DO : documentaion will be updated soon

func GetUser

func GetUser(conditions map[string]string) (*sql.Rows, error)

func HandleError

func HandleError(err error)

HandleError calls crema.PrintfError().

func HandleErrorWithPanic

func HandleErrorWithPanic(err error)

HandleError calls crema.PrintfError(). It then calls panic() which represents a go panic to stop the ordinary flow of control and begins panicking.

func InitDB

func InitDB() *sql.DB

InitDB sets up db connection based on config file TO DO : documentaion will be updated soon

func InitLogFiles

func InitLogFiles()

InitLogFiles initializes the log file The log file will be placed under GOPATH/ named api.log

func LogPrintf

func LogPrintf(data interface{})

LogPrintf calls Printf to print to the log file It also calls log.Println() to print log messages to the standard logger Example output: YYYY-MM-DD HH:MM:SS this is a message log.

func LogPrintfError

func LogPrintfError(data interface{})

LogPrintfError calls file.WriteString() to print error messages to the log file It also calls log.Println() to print log messages to the standard logger Example output: YYYY-MM-DD HH:MM:SS [ERROR] this is an error log.

func MakeGenericDeleteHandler

func MakeGenericDeleteHandler(fn func(*sql.Tx, map[string]string) (sql.Result, error)) http.HandlerFunc

MakeGenericGetHandler creates a generic DELETE-request handler TO DO : documentation will be updated soon

func MakeGenericGetHandler

func MakeGenericGetHandler(fn func(map[string]string) (*sql.Rows, error)) http.HandlerFunc

MakeGenericGetHandler creates a generic GET-request handler TO DO : documentation will be updated soon

func MakeGenericPostHandler

func MakeGenericPostHandler(fn func(*sql.Tx, map[string]string) *sql.Row) http.HandlerFunc

MakeGenericGetHandler creates a generic POST-request handler TO DO : documentation will be updated soon

func MakeGenericPutHandler

func MakeGenericPutHandler(fn func(*sql.Tx, map[string]string) (sql.Result, error)) http.HandlerFunc

MakeGenericGetHandler creates a generic PUT-request handler TO DO : documentation will be updated soon

func PopulateParams

func PopulateParams(params map[string]string, conditions map[string]string)

PopulateParams populates the URI segment params from the incoming requests TO DO: documentation will be updated soon

func PopulateRequestBody

func PopulateRequestBody(r *http.Request, conditions map[string]string)

PopulateRequestBody populates the body from the incoming requests TO DO: documentation will be updated soon

func PopulateSingleValueQueries

func PopulateSingleValueQueries(r *http.Request, conditions map[string]string)

PopulateSingleValueQueries populates query strings from the incoming requests TO DO: documentation will be updated soon

func PostData

func PostData(fn func(*sql.Tx, map[string]string) *sql.Row, w http.ResponseWriter, r *http.Request) (interface{}, int)

PostData performs the standard post mechanism TO DO : documentaion will be updated soon

func PostUser

func PostUser(tx *sql.Tx, values map[string]string) *sql.Row

func Printf

func Printf(data interface{})

Printf calls file.WriteString() to print log messages to the log file Example output: YYYY-MM-DD HH:MM:SS this is a message log.

func PrintfError

func PrintfError(data interface{})

PrintfError calls file.WriteString() to print error messages to the log file Example output: YYYY-MM-DD HH:MM:SS [ERROR] this is an error log.

func PutData

func PutData(fn func(*sql.Tx, map[string]string) (sql.Result, error), w http.ResponseWriter, r *http.Request) (interface{}, int)

PutData performs the standard put mechanism TO DO : documentaion will be updated soon

func PutUser

func PutUser(tx *sql.Tx, values map[string]string) (sql.Result, error)

func ReadDbConfigFile

func ReadDbConfigFile() map[string]string

ReadDbConfigFile reads database configuration inside the config file db.json

func Scan

func Scan(rows *sql.Rows) (interface{}, error)

Scan retrieves data from the sql.Rows dinamically TO DO : documentaion will be updated soon

func SetDB

func SetDB(database *sql.DB)

func SetSigningKey

func SetSigningKey(key string)

SetSigningKey set TO DO : documentaion will be updated soon

func ValidateJWT

func ValidateJWT(tokenString string) error

ValidateJWT validates JWT token TO DO : documentaion will be updated soon

Types

type GenericResponse

type GenericResponse struct {
	Response
	Data interface{} `json:"data"`
}

GenericResponse represents the default response message TO DO: documentation will be updated soon

type Handler

type Handler struct {
	SingleValueQueryString bool
	RawBody                bool
}
var GenericHandler Handler

func (*Handler) DisableRawBody

func (h *Handler) DisableRawBody()

func (*Handler) DisableSingleValueQueryParam

func (h *Handler) DisableSingleValueQueryParam()

func (*Handler) EnableRawBody

func (h *Handler) EnableRawBody()

func (*Handler) EnableSingleValueQueryParam

func (h *Handler) EnableSingleValueQueryParam()

type Query

type Query struct {
	QueryString string
}

func Delete

func Delete() *Query

func GetGenericDeleteQuery

func GetGenericDeleteQuery(table string, conditions map[string]string, key ...string) *Query

func GetGenericInsertQuery

func GetGenericInsertQuery(table string, values map[string]string) *Query

/ERROR BUG for mysql

func GetGenericSelectQuery

func GetGenericSelectQuery(table string, conditions map[string]string, key ...string) *Query

func GetGenericUpdateQuery

func GetGenericUpdateQuery(table string, values map[string]string, key ...string) *Query

ERRO BUG when updating key column

func Insert

func Insert(table string) *Query

func Select

func Select(values ...string) *Query

func Update

func Update(table string) *Query

func (*Query) All

func (q *Query) All() *Query

func (*Query) And

func (q *Query) And() *Query

func (*Query) Asc

func (q *Query) Asc() *Query

func (*Query) Columns

func (q *Query) Columns(columns []string) *Query

func (*Query) Desc

func (q *Query) Desc() *Query

func (*Query) Equal

func (q *Query) Equal(key string, val interface{}) *Query

func (*Query) EqualColumn

func (q *Query) EqualColumn(key string, val string) *Query

func (*Query) EqualMD5

func (q *Query) EqualMD5(key string, val string) *Query

func (*Query) Exists

func (q *Query) Exists() *Query

func (*Query) From

func (q *Query) From(table string) *Query

func (*Query) Greater

func (q *Query) Greater(key string, val interface{}) *Query

func (*Query) GreaterEqual

func (q *Query) GreaterEqual(key string, val interface{}) *Query

func (*Query) InnerJoin

func (q *Query) InnerJoin(table string) *Query

func (*Query) Less

func (q *Query) Less(key string, val interface{}) *Query

func (*Query) LessEqual

func (q *Query) LessEqual(key string, val interface{}) *Query

func (*Query) Like

func (q *Query) Like(key string, val interface{}) *Query

func (*Query) Limit

func (q *Query) Limit(val string) *Query

func (*Query) NotEqual

func (q *Query) NotEqual(key string, val interface{}) *Query

func (*Query) NotEqualColumn

func (q *Query) NotEqualColumn(key string, val string) *Query

func (*Query) On

func (q *Query) On() *Query

func (*Query) Or

func (q *Query) Or() *Query

func (*Query) OrderBy

func (q *Query) OrderBy(column string) *Query

func (*Query) Returning

func (q *Query) Returning(columnName string) *Query

func (*Query) Set

func (q *Query) Set() *Query

func (*Query) Values

func (q *Query) Values(values []string) *Query

func (*Query) Where

func (q *Query) Where() *Query

type Response

type Response struct {
	Status  int    `json:"status"`
	Message string `json:"message"`
}

Response represents the base of a HTTP response message TO DO: documentation will be updated soon

func GenericHTTPResponse

func GenericHTTPResponse(code int) Response

GenericHTTPResponse generates a default HTTP response TO DO: documentation will be updated soon

type Server

type Server struct {
	DB     *sql.DB
	Router *mux.Router
}

func InitServer

func InitServer() *Server

InitServer initializes the core system by setting up the database connection, routing services and system logger

func (*Server) AddRoutes

func (s *Server) AddRoutes(method string, routes string, handler func(http.ResponseWriter, *http.Request))

AddRoutes is used to create HTTP request routing TO DO: documentation to be updated soon

func (*Server) AddRoutesOp

func (s *Server) AddRoutesOp(method string, routes string, handler func(http.ResponseWriter, *http.Request))

AddRoutesOp with Options

Directories

Path Synopsis
src

Jump to

Keyboard shortcuts

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