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. // Error represents an http response error following the api format.
// These are used by the controllers to set the *execution status* // 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 { type Error struct {
Code int Code int
Reason string Reason string

View File

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

View File

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

View File

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

View File

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

View File

@ -15,8 +15,8 @@ type Type struct {
Check func(interface{}) bool 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-s to be used by the framework according to the configuration
type TypeRegistry struct { type Registry struct {
Types []Type // registered Type-s Types []Type // registered Type-s
} }

View File

@ -4,10 +4,13 @@ import (
"fmt" "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" b := "0"
if len(bold) > 0 && bold[0] { if len(bold) > 0 && bold[0] {
b = "1" 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 title_index = 0
var align_offset = 30 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 { func Warn(s ...string) string {
if len(s) == 0 { if len(s) == 0 {
return Color(31, "/!\\") return Color(31, "/!\\")
@ -15,6 +17,9 @@ func Warn(s ...string) string {
return fmt.Sprintf("%s %s", Warn(), s[0]) 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 { func Info(s ...string) string {
if len(s) == 0 { if len(s) == 0 {
return Color(34, "(!)") return Color(34, "(!)")
@ -23,12 +28,14 @@ func Info(s ...string) string {
return fmt.Sprintf("%s %s", Info(), s[0]) return fmt.Sprintf("%s %s", Info(), s[0])
} }
// Title prints a formatted title (auto-indexed from local counted)
func Title(s string) { func Title(s string) {
title_index++ title_index++
fmt.Printf("\n%s |%d| %s %s\n", Color(33, ">>", false), title_index, s, Color(33, "<<", false)) 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) { func Align(s string) {
// 1. print 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 // returns the farthest matching child
// //
// @path the path to browse // @path the path to browse

View File

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

View File

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

View File

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

View File

@ -11,7 +11,7 @@ import (
func NewDataset() *DataSet { func NewDataset() *DataSet {
return &DataSet{ return &DataSet{
Uri: make([]*Parameter, 0), URI: make([]*Parameter, 0),
Get: make(map[string]*Parameter), Get: make(map[string]*Parameter),
Form: make(map[string]*Parameter), Form: make(map[string]*Parameter),
Set: 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' // with creating pointers inside 'Url'
func (i *DataSet) SetUri(data []string) { func (i *DataSet) SetURI(data []string) {
for index, value := range data { for index, value := range data {
@ -50,7 +50,7 @@ func (i *DataSet) SetUri(data []string) {
} }
// create link in 'Url' // 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 // parse json
if strings.HasPrefix(contentType, "application/json") { if strings.HasPrefix(contentType, "application/json") {
i.parseJson(req) i.parseJSON(req)
return return
} }
@ -113,9 +113,9 @@ func (i *DataSet) fetchForm(req *http.Request) {
// if unknown type store nothing // 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' // and 'Set'
func (i *DataSet) parseJson(req *http.Request) { func (i *DataSet) parseJSON(req *http.Request) {
parsed := make(map[string]interface{}, 0) parsed := make(map[string]interface{}, 0)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
package response 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 { func (i Arguments) Has(key string) bool {
_, exists := i[key] _, exists := i[key]
return exists return exists

View File

@ -4,7 +4,7 @@ import (
"git.xdrm.io/go/aicra/err" "git.xdrm.io/go/aicra/err"
) )
func NewResponse() *Response { func New() *Response {
return &Response{ return &Response{
data: make(map[string]interface{}), data: make(map[string]interface{}),
Err: err.Success, 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) { func (s *Server) routeRequest(res http.ResponseWriter, httpReq *http.Request) {
/* (1) Build request */ /* (1) Build request */
req, err := request.BuildFromHttpRequest(httpReq) req, err := request.BuildFromHTTPRequest(httpReq)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -112,7 +112,7 @@ func (s *Server) routeRequest(res http.ResponseWriter, httpReq *http.Request) {
parameters["_SCOPE_"] = scope parameters["_SCOPE_"] = scope
/* (3) Execute */ /* (3) Execute */
response := callable(parameters, response.NewResponse()) response := callable(parameters, response.New())
/* (4) Extract http headers */ /* (4) Extract http headers */
for k, v := range response.Dump() { for k, v := range response.Dump() {

View File

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

View File

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