DB is pointer to gorm.DB that can be used directly for ORM and database
var DB *gorm.DB
ErrInternalServerError is general error that will be send if there is unexpected error on the server
var ErrInternalServerError = ErrorAPI{ StatusCode: http.StatusInternalServerError, Code: "internal_server_error", Message: "Error occured while processing the request", }
ErrJSONParseFailed will be returned when calling req.DeserializeRequestData but with bad JSON. For example, int field that supplied with string
var ErrJSONParseFailed = ErrorAPI{ StatusCode: http.StatusBadRequest, Code: "failed_to_parse_json", Message: "Failed to parse json request", }
ErrUnsupportedContentType returned when request has content-type header that is unsupported
var ErrUnsupportedContentType = ErrorAPI{ StatusCode: http.StatusUnsupportedMediaType, Code: "unsupported_content_type", Message: "Currently, we are accepting application/json only", }
func Handle(f HTTPHandler) func(http.ResponseWriter, *http.Request)
Handle the http request using the HTTPHandler, without middleware
func WithMiddleware(f HTTPHandler, m []Middleware) func(http.ResponseWriter, *http.Request)
WithMiddleware wrapped the http request to Request object, pass it to middleware, start from first middleware in m to the last.
Error is interface of error that can be thrown for response
type Error interface { GetMessage() map[string]interface{} GetStatusCode() int }
ErrorAPI is standardized error of Charon app
type ErrorAPI struct { StatusCode int Code string Message string }
func (apiError ErrorAPI) GetMessage() map[string]interface{}
GetMessage returns the message to shown as response body
func (apiError ErrorAPI) GetStatusCode() int
GetStatusCode returns the http status code
ErrorForm is common error, usually after parsing the request body
type ErrorForm struct { Code string ErrorFormField ErrorFormFieldNested NonErrorFormField ErrorFormFieldAtomic }
func (formError ErrorForm) GetMessage() map[string]interface{}
GetMessage returns the message to shown as response body it will include code (unique identifier) and map as message the message will contain field name as key and error as value
func (formError ErrorForm) GetStatusCode() int
GetStatusCode returns HTTP 400 Bad Request code
func (formError ErrorForm) IsError() bool
IsError returns true if there is at least one error, and return false if there is no error on the struct
ErrorFormField is the interface of error for a field in a form. A field in a form can be: - an atomic field (ex: username, fullname), using ErrorFormFieldAtomic - an array field (ex: todos, checkboxes), using ErrorFormFieldArray - a nested field (ex: address consist of zip code, city), using ErrorFormFieldNested
type ErrorFormField interface { GetMessage() interface{} IsError() bool }
ErrorFormFieldArray is error representation of array field, example:
todosErr := ErrorFormFieldArray{ErrorFormFieldAtomic{"todo can't be empty"}, ErrorFormFieldAtomic{}, ErrorFormFieldAtomic{"todo is duplicate"}} // will be converted to json: [["todo can't be empty"],[],["todo is duplicate"]]
type ErrorFormFieldArray []ErrorFormField
func (err ErrorFormFieldArray) GetMessage() interface{}
GetMessage returns json-friendly array copy of the error
func (err ErrorFormFieldArray) IsError() bool
IsError returns true if there is at least one member with err. Tt will iterate all the member.
ErrorFormFieldAtomic is error representation of one field, example:
passwordErr := ErrorFormFieldAtomic{"password is too short". "password must include symbol"} // will be converted to json: ["password is too short","password must include symbol"]
type ErrorFormFieldAtomic []string
func (err ErrorFormFieldAtomic) GetMessage() interface{}
GetMessage returns the json-friendly array copy of the error
func (err ErrorFormFieldAtomic) IsError() bool
IsError returns true if there is any error
ErrorFormFieldNested is error representation other field error mapped by field name, example:
addressErr := ErrorFormFieldNested{ "zipCode": ErrorFormFieldAtomic{"zip code is invalid"}, "city": ErrorFormFieldAtomic{"city can't be empty"}, } // will be converted to json: {"city":["city can't be empty"],"zipCode":["zip code is invalid"]}
type ErrorFormFieldNested map[string]ErrorFormField
func (err ErrorFormFieldNested) GetMessage() interface{}
GetMessage returns json-friendly map copy of the error
func (err ErrorFormFieldNested) IsError() bool
IsError returns true if there is at least one member with err. It will iterate all the member.
HTTPHandler receive Helios wrapped request and ressponse
type HTTPHandler func(Request)
HTTPRequest wrapper of Helios Http Request r is the HTTP Request, containing request data w is the HTTP Response writer, to write HTTP reply s is the session of current request, using gorilla/sessions package c is the context of the current request, can be used for user data, etc u is the url params argument
type HTTPRequest struct {
// contains filtered or unexported fields
}
func NewHTTPRequest(w http.ResponseWriter, r *http.Request) HTTPRequest
NewHTTPRequest wraps usual http request and response writer to HTTPRequest struct
func (req *HTTPRequest) ClientIP() string
ClientIP returns the original ip address of the request. First, it checks for X-Forwarded-For and X-Real-Ip http header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For) If they are not present, return the http.Request.RemoteAddr The priority is: X-Forwarded-For, X-Real-Ip, RemoteAddr
func (req *HTTPRequest) DeserializeRequestData(obj interface{}) Error
DeserializeRequestData deserializes the request body and parse it into pointer to struct
func (req *HTTPRequest) GetContextData(key string) interface{}
GetContextData return the data of session with known key
func (req *HTTPRequest) GetHeader(key string) string
GetHeader gets the header of request
func (req *HTTPRequest) GetSessionData(key string) interface{}
GetSessionData return the data of session with known key
func (req *HTTPRequest) GetURLParam(key string) string
GetURLParam returns the parameter of the request url
func (req *HTTPRequest) GetURLParamUint(key string) (uint, error)
GetURLParamUint returns the parameter of the request url as unisgned int
func (req *HTTPRequest) SaveSession()
SaveSession saves the session to the cookie
func (req *HTTPRequest) SendJSON(output interface{}, code int)
SendJSON write json as http response
func (req *HTTPRequest) SetContextData(key string, value interface{})
SetContextData set the data of session
func (req *HTTPRequest) SetHeader(key string, value string)
SetHeader sets the header of response writer
func (req *HTTPRequest) SetSessionData(key string, value interface{})
SetSessionData set the data of session
Helios is the core of the apps
type Helios struct {
// contains filtered or unexported fields
}
App will be the core app that has all the models and be the core of the server
var App Helios
func (app *Helios) BeforeTest()
BeforeTest has to be called everytime a test is run It will reset the database
func (app *Helios) CloseDB()
CloseDB close the database connection
func (app *Helios) Initialize() error
Initialize the database to production database
func (app *Helios) Migrate()
Migrate migrate all the models
func (app *Helios) RegisterModel(model interface{})
RegisterModel so the database will be migrated
Middleware is a function that receive an HTTPHandler and return new HTTPHandler
type Middleware func(HTTPHandler) HTTPHandler
func CreateCORSMiddleware(allowedOrigins []string) Middleware
CreateCORSMiddleware add Access-Control-Allow-Origin headers to the response.
MockRequest is Request object that is mocked for testing purposes
type MockRequest struct { RequestData interface{} RequestHeader map[string]string ResponseHeader map[string]string SessionData map[string]interface{} ContextData map[string]interface{} JSONResponse []byte StatusCode int URLParam map[string]string RemoteAddr string }
func NewMockRequest() MockRequest
NewMockRequest returns new MockRequest with empty data RemoteAddr is set to 127.0.0.1 in default
func (req *MockRequest) ClientIP() string
ClientIP returns RemoteAddr data of req
func (req *MockRequest) DeserializeRequestData(obj interface{}) Error
DeserializeRequestData return the data of request
func (req *MockRequest) GetContextData(key string) interface{}
GetContextData return the data of session with known key
func (req *MockRequest) GetHeader(key string) string
GetHeader gets the header of request
func (req *MockRequest) GetSessionData(key string) interface{}
GetSessionData return the data of session with known key
func (req *MockRequest) GetURLParam(key string) string
GetURLParam returns the url param of given key
func (req *MockRequest) GetURLParamUint(key string) (uint, error)
GetURLParamUint returns the parameter of the request url as unisgned int
func (req *MockRequest) SaveSession()
SaveSession do nothing because the session is already saved
func (req *MockRequest) SendJSON(output interface{}, code int)
SendJSON write json as http response
func (req *MockRequest) SetContextData(key string, value interface{})
SetContextData set the data of session
func (req *MockRequest) SetHeader(key string, value string)
SetHeader sets the header of response writer
func (req *MockRequest) SetSessionData(key string, value interface{})
SetSessionData set the data of session
Request interface of Helios Http Request Wrapper
type Request interface { DeserializeRequestData(obj interface{}) Error GetURLParam(key string) string GetURLParamUint(key string) (uint, error) GetContextData(key string) interface{} SetContextData(key string, value interface{}) GetSessionData(key string) interface{} SetSessionData(key string, value interface{}) SaveSession() ClientIP() string GetHeader(key string) string SetHeader(key string, value string) SendJSON(output interface{}, code int) }