LINT: renaming + refactor

This commit is contained in:
Adrien Marquès 2018-07-09 01:34:21 +02:00
parent 2f7332a256
commit 637bc91770
23 changed files with 94 additions and 79 deletions

View File

@ -7,7 +7,7 @@ import (
// Error represents an http response error following the api format.
// These are used by the controllers to set the *execution status*
// directly into the response as JSON.
// directly into the response as JSON alongside response output fields.
type Error struct {
Code int
Reason string

View File

@ -1,9 +1,11 @@
package main
// Match matches the string 'any'
func Match(name string) bool {
return name == "any"
}
// Check always returns true
func Check(value interface{}) bool {
return true
}

View File

@ -19,10 +19,12 @@ var validationTable = map[reflect.Kind]interface{}{
reflect.Uint64: nil,
}
// Match matches the string 'int'
func Match(name string) bool {
return name == "int"
}
// Check returns true for any type from the @validationTable
func Check(value interface{}) bool {
kind := reflect.TypeOf(value).Kind()

View File

@ -5,8 +5,8 @@ import (
"strconv"
)
var min *uint64 = nil
var max *uint64 = nil
var min *uint64
var max *uint64
func Match(name string) bool {

View File

@ -11,10 +11,10 @@ import (
// CreateRegistry creates an empty type registry
// - if loadDir is True if will load all available types
// inside the local ./types folder
func CreateRegistry(loadDir ...string) *TypeRegistry {
func CreateRegistry(loadDir ...string) *Registry {
/* (1) Create registry */
reg := &TypeRegistry{
reg := &Registry{
Types: make([]Type, 0),
}
@ -50,7 +50,7 @@ func CreateRegistry(loadDir ...string) *TypeRegistry {
// Add adds a type to the registry; it must be a
// valid and existing plugin name with or without the .so extension
// it must be located in the relative directory ./types
func (tr *TypeRegistry) Add(pluginName string) error {
func (tr *Registry) Add(pluginName string) error {
/* (1) Check plugin name */
if len(pluginName) < 1 {
@ -104,16 +104,18 @@ func (tr *TypeRegistry) Add(pluginName string) error {
return nil
}
// Checks the 'value' which must be of type 'name'
func (tr TypeRegistry) Run(name string, value interface{}) error {
// Run finds a type checker from the registry matching the type @typeName
// and uses this checker to check the @value. If no type checker matches
// the @typeName name, error is returned by default.
func (tr Registry) Run(typeName string, value interface{}) error {
var T *Type = nil
var T *Type
/* (1) Iterate to find matching type (take first) */
for _, t := range tr.Types {
// stop if found
if t.Match(name) {
if t.Match(typeName) {
T = &t
break
}

View File

@ -15,8 +15,8 @@ type Type struct {
Check func(interface{}) bool
}
// TypeRegistry represents a registry containing all available
// Registry represents a registry containing all available
// Type-s to be used by the framework according to the configuration
type TypeRegistry struct {
type Registry struct {
Types []Type // registered Type-s
}

View File

@ -4,10 +4,13 @@ import (
"fmt"
)
func Color(color byte, s string, bold ...bool) string {
// Color returns a bash-formatted string representing
// the string @text with the color code @color and in bold
// if @bold (1 optional argument) is set to true
func Color(color byte, text string, bold ...bool) string {
b := "0"
if len(bold) > 0 && bold[0] {
b = "1"
}
return fmt.Sprintf("\033[%s;%dm%s\033[0m", b, color, s)
return fmt.Sprintf("\033[%s;%dm%s\033[0m", b, color, text)
}

View File

@ -8,6 +8,8 @@ import (
var title_index = 0
var align_offset = 30
// Warn returns a red warning ASCII sign. If a string is given
// as argument, it will print it after the warning sign
func Warn(s ...string) string {
if len(s) == 0 {
return Color(31, "/!\\")
@ -15,6 +17,9 @@ func Warn(s ...string) string {
return fmt.Sprintf("%s %s", Warn(), s[0])
}
// Info returns a blue info ASCII sign. If a string is given
// as argument, it will print it after the info sign
func Info(s ...string) string {
if len(s) == 0 {
return Color(34, "(!)")
@ -23,12 +28,14 @@ func Info(s ...string) string {
return fmt.Sprintf("%s %s", Info(), s[0])
}
// Title prints a formatted title (auto-indexed from local counted)
func Title(s string) {
title_index++
fmt.Printf("\n%s |%d| %s %s\n", Color(33, ">>", false), title_index, s, Color(33, "<<", false))
}
// Align prints strings with space padding to align line ends (fixed width)
func Align(s string) {
// 1. print string

View File

@ -73,7 +73,7 @@ func (c Controller) Method(method string) *Method {
}
// Browses tries to browse the controller childtree and
// Browse tries to browse the controller childtree and
// returns the farthest matching child
//
// @path the path to browse

View File

@ -6,7 +6,7 @@ import (
)
// Read all until the next boundary is found
func (i *MultipartReader) readComponent() ([]string, error) {
func (i *Reader) readComponent() ([]string, error) {
component := make([]string, 0)
@ -34,7 +34,7 @@ func (i *MultipartReader) readComponent() ([]string, error) {
}
// Parses a single component from its raw lines
func (i *MultipartReader) parseComponent(line []string) error {
func (i *Reader) parseComponent(line []string) error {
// next line index to use
cursor := 1
@ -69,7 +69,7 @@ func (i *MultipartReader) parseComponent(line []string) error {
already, isset := i.Components[name]
if !isset {
i.Components[name] = &MultipartComponent{
i.Components[name] = &Component{
File: isFile,
Data: make([]string, 0),
}

View File

@ -8,18 +8,18 @@ import (
"net/http"
)
// Creates a new multipart reader from an http.Request
func CreateReader(req *http.Request) *MultipartReader {
// CreateReader creates a new multipart reader from an http.Request
func CreateReader(req *http.Request) *Reader {
/* (1) extract boundary */
boundary := req.Header.Get("Content-Type")[len("multipart/form-data; boundary="):]
boundary = fmt.Sprintf("--%s", boundary)
/* (2) init reader */
i := &MultipartReader{
i := &Reader{
reader: bufio.NewReader(req.Body),
boundary: boundary,
Components: make(map[string]*MultipartComponent),
Components: make(map[string]*Component),
}
/* (3) Place reader cursor after first boundary */
@ -36,8 +36,8 @@ func CreateReader(req *http.Request) *MultipartReader {
}
// Parses the multipart components from the request
func (i *MultipartReader) Parse() error {
// Parse parses the multipart components from the request
func (i *Reader) Parse() error {
/* (1) For each component (until boundary) */
for {

View File

@ -4,7 +4,8 @@ import (
"bufio"
)
type MultipartReader struct {
// Reader represents a multipart reader
type Reader struct {
// reader used for http.Request.Body reading
reader *bufio.Reader
@ -12,11 +13,11 @@ type MultipartReader struct {
boundary string
// result will be inside this field
Components map[string]*MultipartComponent
Components map[string]*Component
}
// Represents a multipart component
type MultipartComponent struct {
// Component represents a multipart component
type Component struct {
// whether this component is a file
// if not, it is a simple variable data
File bool

View File

@ -11,7 +11,7 @@ import (
func NewDataset() *DataSet {
return &DataSet{
Uri: make([]*Parameter, 0),
URI: make([]*Parameter, 0),
Get: make(map[string]*Parameter),
Form: make(map[string]*Parameter),
Set: make(map[string]*Parameter),
@ -34,9 +34,9 @@ func (i *DataSet) Build(req *http.Request) {
}
// setUriData stores URL data and fills 'Set'
// SetURI stores URL data and fills 'Set'
// with creating pointers inside 'Url'
func (i *DataSet) SetUri(data []string) {
func (i *DataSet) SetURI(data []string) {
for index, value := range data {
@ -50,7 +50,7 @@ func (i *DataSet) SetUri(data []string) {
}
// create link in 'Url'
i.Uri = append(i.Uri, i.Set[setindex])
i.URI = append(i.URI, i.Set[setindex])
}
@ -94,7 +94,7 @@ func (i *DataSet) fetchForm(req *http.Request) {
// parse json
if strings.HasPrefix(contentType, "application/json") {
i.parseJson(req)
i.parseJSON(req)
return
}
@ -113,9 +113,9 @@ func (i *DataSet) fetchForm(req *http.Request) {
// if unknown type store nothing
}
// parseJson parses JSON from the request body inside 'Form'
// parseJSON parses JSON from the request body inside 'Form'
// and 'Set'
func (i *DataSet) parseJson(req *http.Request) {
func (i *DataSet) parseJSON(req *http.Request) {
parsed := make(map[string]interface{}, 0)

View File

@ -12,16 +12,16 @@ import (
"time"
)
// BuildFromHttpRequest builds an interface request from a http.Request
func BuildFromHttpRequest(req *http.Request) (*Request, error) {
// BuildFromHTTPRequest builds an interface request from a http.Request
func BuildFromHTTPRequest(req *http.Request) (*Request, error) {
/* (1) Get useful data */
uri := normaliseUri(req.URL.Path)
uri := normaliseURI(req.URL.Path)
uriparts := strings.Split(uri, "/")
/* (2) Init request */
inst := &Request{
Uri: uriparts,
URI: uriparts,
Path: make([]string, 0, len(uriparts)),
Data: NewDataset(),
}

View File

@ -3,7 +3,7 @@ package request
type Request struct {
// corresponds to the list of uri components
// featuring in the request URI
Uri []string
URI []string
// controller path (portion of 'Uri')
Path []string
@ -18,7 +18,7 @@ type DataSet struct {
// catches all after the controller path
//
// points to Request.Data
Uri []*Parameter
URI []*Parameter
// uri parameters following the QUERY format
//

View File

@ -7,9 +7,9 @@ import (
"strings"
)
// normaliseUri removes the trailing '/' to always
// normaliseURI removes the trailing '/' to always
// have the same Uri format for later processing
func normaliseUri(uri string) string {
func normaliseURI(uri string) string {
if len(uri) < 1 {
return uri
@ -62,9 +62,9 @@ func parseParameter(data interface{}) interface{} {
}
return parseParameter(element.String())
// 3. Return all elements if more than 1
} else {
}
// 3. Return all elements if more than 1
result := make([]interface{}, dvalue.Len())
for i, l := 0, dvalue.Len(); i < l; i++ {
@ -79,8 +79,6 @@ func parseParameter(data interface{}) interface{} {
}
return result
}
/* (2) string -> parse */
case reflect.String:

View File

@ -12,10 +12,10 @@ import (
// CreateRegistry creates an empty middleware registry
// - if loadDir is set -> load all available middlewares
// inside the local ./middleware folder
func CreateRegistry(loadDir ...string) *MiddlewareRegistry {
func CreateRegistry(loadDir ...string) *Registry {
/* (1) Create registry */
reg := &MiddlewareRegistry{
reg := &Registry{
Middlewares: make([]MiddleWare, 0),
}
@ -51,7 +51,7 @@ func CreateRegistry(loadDir ...string) *MiddlewareRegistry {
// Add adds a middleware to the registry; it must be a
// valid and existing plugin name with or without the .so extension
// it must be located in the relative directory .build/middleware
func (tr *MiddlewareRegistry) Add(pluginName string) error {
func (reg *Registry) Add(pluginName string) error {
/* (1) Check plugin name */
if len(pluginName) < 1 {
@ -87,21 +87,21 @@ func (tr *MiddlewareRegistry) Add(pluginName string) error {
}
/* (7) Add type to registry */
tr.Middlewares = append(tr.Middlewares, MiddleWare{
reg.Middlewares = append(reg.Middlewares, MiddleWare{
Inspect: inspectCast,
})
return nil
}
// Runs all middlewares (default browse order)
func (mr MiddlewareRegistry) Run(req http.Request) Scope {
// Run executes all middlewares (default browse order)
func (reg Registry) Run(req http.Request) Scope {
/* (1) Initialise scope */
scope := Scope{}
/* (2) Execute each middleware */
for _, m := range mr.Middlewares {
for _, m := range reg.Middlewares {
m.Inspect(req, &scope)
}

View File

@ -13,14 +13,14 @@ type Scope []string
// the @http.Request
type Inspector func(http.Request, *Scope)
// Middleware contains all necessary methods
// MiddleWare contains all necessary methods
// for a Middleware provided by user/developer
type MiddleWare struct {
Inspect func(http.Request, *Scope)
}
// MiddlewareRegistry represents a registry containing all registered
// Registry represents a registry containing all registered
// middlewares to be processed before routing any request
type MiddlewareRegistry struct {
type Registry struct {
Middlewares []MiddleWare
}

View File

@ -1,6 +1,6 @@
package response
// Checks whether a key exists in the arguments
// Has checks whether a key exists in the arguments
func (i Arguments) Has(key string) bool {
_, exists := i[key]
return exists

View File

@ -4,7 +4,7 @@ import (
"git.xdrm.io/go/aicra/err"
)
func NewResponse() *Response {
func New() *Response {
return &Response{
data: make(map[string]interface{}),
Err: err.Success,

View File

@ -53,7 +53,7 @@ func (s *Server) Listen(port uint16) error {
func (s *Server) routeRequest(res http.ResponseWriter, httpReq *http.Request) {
/* (1) Build request */
req, err := request.BuildFromHttpRequest(httpReq)
req, err := request.BuildFromHTTPRequest(httpReq)
if err != nil {
log.Fatal(err)
}
@ -112,7 +112,7 @@ func (s *Server) routeRequest(res http.ResponseWriter, httpReq *http.Request) {
parameters["_SCOPE_"] = scope
/* (3) Execute */
response := callable(parameters, response.NewResponse())
response := callable(parameters, response.New())
/* (4) Extract http headers */
for k, v := range response.Dump() {

View File

@ -13,6 +13,6 @@ import (
type Server struct {
config *config.Controller
Params map[string]interface{}
Checker *checker.TypeRegistry // type check
Middleware *middleware.MiddlewareRegistry // middlewares
Checker *checker.Registry // type check
Middleware *middleware.Registry // middlewares
}

View File

@ -13,14 +13,14 @@ import (
func (s *Server) findController(req *request.Request) *config.Controller {
/* (1) Try to browse by URI */
pathi, ctl := s.config.Browse(req.Uri)
pathi, ctl := s.config.Browse(req.URI)
/* (2) Set controller uri */
req.Path = make([]string, 0, pathi)
req.Path = append(req.Path, req.Uri[:pathi]...)
req.Path = append(req.Path, req.URI[:pathi]...)
/* (3) Extract & store URI params */
req.Data.SetUri(req.Uri[pathi:])
req.Data.SetURI(req.URI[pathi:])
/* (4) Return controller */
return ctl