mirror of
https://github.com/kataras/iris.git
synced 2025-12-24 05:17:03 +00:00
Publish the new version ✈️ | Look description please!
# FAQ ### Looking for free support? http://support.iris-go.com https://kataras.rocket.chat/channel/iris ### Looking for previous versions? https://github.com/kataras/iris#version ### Should I upgrade my Iris? Developers are not forced to upgrade if they don't really need it. Upgrade whenever you feel ready. > Iris uses the [vendor directory](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo) feature, so you get truly reproducible builds, as this method guards against upstream renames and deletes. **How to upgrade**: Open your command-line and execute this command: `go get -u github.com/kataras/iris`. For further installation support, please click [here](http://support.iris-go.com/d/16-how-to-install-iris-web-framework). ### About our new home page http://iris-go.com Thanks to [Santosh Anand](https://github.com/santoshanand) the http://iris-go.com has been upgraded and it's really awesome! [Santosh](https://github.com/santoshanand) is a freelancer, he has a great knowledge of nodejs and express js, Android, iOS, React Native, Vue.js etc, if you need a developer to find or create a solution for your problem or task, please contact with him. The amount of the next two or three donations you'll send they will be immediately transferred to his own account balance, so be generous please! Read more at https://github.com/kataras/iris/blob/master/HISTORY.md Former-commit-id: eec2d71bbe011d6b48d2526eb25919e36e5ad94e
This commit is contained in:
122
core/router/macro/interpreter/ast/ast.go
Normal file
122
core/router/macro/interpreter/ast/ast.go
Normal file
@@ -0,0 +1,122 @@
|
||||
// Copyright 2017 Gerasimos Maropoulos. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package ast
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type ParamType uint8
|
||||
|
||||
const (
|
||||
ParamTypeUnExpected ParamType = iota
|
||||
// /myparam1
|
||||
ParamTypeString
|
||||
// /42
|
||||
ParamTypeInt
|
||||
// /myparam
|
||||
ParamTypeAlphabetical
|
||||
// /main.css
|
||||
ParamTypeFile
|
||||
// /myparam1/myparam2
|
||||
ParamTypePath
|
||||
)
|
||||
|
||||
var paramTypes = map[string]ParamType{
|
||||
"string": ParamTypeString,
|
||||
"int": ParamTypeInt,
|
||||
"alphabetical": ParamTypeAlphabetical,
|
||||
"file": ParamTypeFile,
|
||||
"path": ParamTypePath,
|
||||
// could be named also:
|
||||
// "tail":
|
||||
// "wild"
|
||||
// "wildcard"
|
||||
|
||||
}
|
||||
|
||||
func LookupParamType(ident string) ParamType {
|
||||
if typ, ok := paramTypes[ident]; ok {
|
||||
return typ
|
||||
}
|
||||
return ParamTypeUnExpected
|
||||
}
|
||||
|
||||
type ParamStatement struct {
|
||||
Src string // the original unparsed source, i.e: {id:int range(1,5) else 404}
|
||||
Name string // id
|
||||
Type ParamType // int
|
||||
Funcs []ParamFunc // range
|
||||
ErrorCode int // 404
|
||||
}
|
||||
|
||||
type ParamFuncArg interface{}
|
||||
|
||||
func ParamFuncArgInt64(a ParamFuncArg) (int64, bool) {
|
||||
if v, ok := a.(int64); ok {
|
||||
return v, false
|
||||
}
|
||||
return -1, false
|
||||
}
|
||||
|
||||
func ParamFuncArgToInt64(a ParamFuncArg) (int64, error) {
|
||||
switch a.(type) {
|
||||
case int64:
|
||||
return a.(int64), nil
|
||||
case string:
|
||||
return strconv.ParseInt(a.(string), 10, 64)
|
||||
case int:
|
||||
return int64(a.(int)), nil
|
||||
default:
|
||||
return -1, fmt.Errorf("unexpected function argument type: %q", a)
|
||||
}
|
||||
}
|
||||
|
||||
func ParamFuncArgInt(a ParamFuncArg) (int, bool) {
|
||||
if v, ok := a.(int); ok {
|
||||
return v, false
|
||||
}
|
||||
return -1, false
|
||||
}
|
||||
|
||||
func ParamFuncArgToInt(a ParamFuncArg) (int, error) {
|
||||
switch a.(type) {
|
||||
case int:
|
||||
return a.(int), nil
|
||||
case string:
|
||||
return strconv.Atoi(a.(string))
|
||||
case int64:
|
||||
return int(a.(int64)), nil
|
||||
default:
|
||||
return -1, fmt.Errorf("unexpected function argument type: %q", a)
|
||||
}
|
||||
}
|
||||
|
||||
func ParamFuncArgString(a ParamFuncArg) (string, bool) {
|
||||
if v, ok := a.(string); ok {
|
||||
return v, false
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func ParamFuncArgToString(a ParamFuncArg) (string, error) {
|
||||
switch a.(type) {
|
||||
case string:
|
||||
return a.(string), nil
|
||||
case int:
|
||||
return strconv.Itoa(a.(int)), nil
|
||||
case int64:
|
||||
return strconv.FormatInt(a.(int64), 10), nil
|
||||
default:
|
||||
return "", fmt.Errorf("unexpected function argument type: %q", a)
|
||||
}
|
||||
}
|
||||
|
||||
// range(1,5)
|
||||
type ParamFunc struct {
|
||||
Name string // range
|
||||
Args []ParamFuncArg // [1,5]
|
||||
}
|
||||
186
core/router/macro/interpreter/lexer/lexer.go
Normal file
186
core/router/macro/interpreter/lexer/lexer.go
Normal file
@@ -0,0 +1,186 @@
|
||||
// Copyright 2017 Gerasimos Maropoulos. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package lexer
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris/core/router/macro/interpreter/token"
|
||||
)
|
||||
|
||||
type Lexer struct {
|
||||
input string
|
||||
pos int // current pos in input, current char
|
||||
readPos int // current reading pos in input, after current char
|
||||
ch byte // current char under examination
|
||||
}
|
||||
|
||||
func New(src string) *Lexer {
|
||||
l := &Lexer{
|
||||
input: src,
|
||||
}
|
||||
// step to the first character in order to be ready
|
||||
l.readChar()
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *Lexer) readChar() {
|
||||
if l.readPos >= len(l.input) {
|
||||
l.ch = 0
|
||||
} else {
|
||||
l.ch = l.input[l.readPos]
|
||||
}
|
||||
l.pos = l.readPos
|
||||
l.readPos += 1
|
||||
}
|
||||
|
||||
const (
|
||||
Begin = '{' // token.LBRACE
|
||||
End = '}' // token.RBRACE
|
||||
)
|
||||
|
||||
func resolveTokenType(ch byte) token.TokenType {
|
||||
switch ch {
|
||||
case Begin:
|
||||
return token.LBRACE
|
||||
case End:
|
||||
return token.RBRACE
|
||||
// Let's keep it simple, no evaluation for logical operators, we are not making a new programming language, keep it simple makis.
|
||||
// ||
|
||||
// case '|':
|
||||
// if l.peekChar() == '|' {
|
||||
// ch := l.ch
|
||||
// l.readChar()
|
||||
// t = token.Token{Type: token.OR, Literal: string(ch) + string(l.ch)}
|
||||
// }
|
||||
// ==
|
||||
case ':':
|
||||
return token.COLON
|
||||
case '(':
|
||||
return token.LPAREN
|
||||
case ')':
|
||||
return token.RPAREN
|
||||
case ',':
|
||||
return token.COMMA
|
||||
// literals
|
||||
case 0:
|
||||
return token.EOF
|
||||
default:
|
||||
return token.IDENT //
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (l *Lexer) NextToken() (t token.Token) {
|
||||
l.skipWhitespace()
|
||||
typ := resolveTokenType(l.ch)
|
||||
t.Type = typ
|
||||
switch typ {
|
||||
case token.EOF:
|
||||
t.Literal = ""
|
||||
case token.IDENT:
|
||||
if isLetter(l.ch) {
|
||||
// letters
|
||||
lit := l.readIdentifier()
|
||||
typ := token.LookupIdent(lit)
|
||||
t = l.newToken(typ, lit)
|
||||
return
|
||||
}
|
||||
if isDigit(l.ch) {
|
||||
// numbers
|
||||
lit := l.readNumber()
|
||||
t = l.newToken(token.INT, lit)
|
||||
return
|
||||
}
|
||||
|
||||
t = l.newTokenRune(token.ILLEGAL, l.ch)
|
||||
default:
|
||||
t = l.newTokenRune(typ, l.ch)
|
||||
}
|
||||
l.readChar() // set the pos to the next
|
||||
return
|
||||
}
|
||||
|
||||
func (l *Lexer) NextDynamicToken() (t token.Token) {
|
||||
// calculate anything, even spaces.
|
||||
|
||||
// numbers
|
||||
lit := l.readNumber()
|
||||
if lit != "" {
|
||||
return l.newToken(token.INT, lit)
|
||||
}
|
||||
|
||||
lit = l.readIdentifierFuncArgument()
|
||||
return l.newToken(token.IDENT, lit)
|
||||
}
|
||||
|
||||
// used to skip any illegal token if inside parenthesis, used to be able to set custom regexp inside a func.
|
||||
func (l *Lexer) readIdentifierFuncArgument() string {
|
||||
pos := l.pos
|
||||
for resolveTokenType(l.ch) != token.RPAREN {
|
||||
l.readChar()
|
||||
}
|
||||
|
||||
return l.input[pos:l.pos]
|
||||
}
|
||||
|
||||
// useful when we want to peek but no continue, i.e empty param functions 'even()'
|
||||
func (l *Lexer) PeekNextTokenType() token.TokenType {
|
||||
if len(l.input)-1 > l.pos {
|
||||
ch := l.input[l.pos]
|
||||
return resolveTokenType(ch)
|
||||
}
|
||||
return resolveTokenType(0) // EOF
|
||||
}
|
||||
|
||||
func (l *Lexer) newToken(tokenType token.TokenType, lit string) token.Token {
|
||||
t := token.Token{
|
||||
Type: tokenType,
|
||||
Literal: lit,
|
||||
Start: l.pos,
|
||||
End: l.pos,
|
||||
}
|
||||
// remember, l.pos is the last char
|
||||
// and we want to include both start and end
|
||||
// in order to be easy to the user to see by just marking the expression
|
||||
if l.pos > 1 && len(lit) > 1 {
|
||||
t.End = l.pos - 1
|
||||
t.Start = t.End - len(lit) + 1
|
||||
}
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
func (l *Lexer) newTokenRune(tokenType token.TokenType, ch byte) token.Token {
|
||||
return l.newToken(tokenType, string(ch))
|
||||
}
|
||||
|
||||
func (l *Lexer) skipWhitespace() {
|
||||
for l.ch == ' ' || l.ch == '\t' || l.ch == '\n' || l.ch == '\r' {
|
||||
l.readChar()
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Lexer) readIdentifier() string {
|
||||
pos := l.pos
|
||||
for isLetter(l.ch) {
|
||||
l.readChar()
|
||||
}
|
||||
return l.input[pos:l.pos]
|
||||
}
|
||||
|
||||
func isLetter(ch byte) bool {
|
||||
return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_'
|
||||
}
|
||||
|
||||
func (l *Lexer) readNumber() string {
|
||||
pos := l.pos
|
||||
for isDigit(l.ch) {
|
||||
l.readChar()
|
||||
}
|
||||
return l.input[pos:l.pos]
|
||||
}
|
||||
|
||||
func isDigit(ch byte) bool {
|
||||
return '0' <= ch && ch <= '9'
|
||||
}
|
||||
58
core/router/macro/interpreter/lexer/lexer_test.go
Normal file
58
core/router/macro/interpreter/lexer/lexer_test.go
Normal file
@@ -0,0 +1,58 @@
|
||||
// Copyright 2017 Gerasimos Maropoulos. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package lexer
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris/core/router/macro/interpreter/token"
|
||||
)
|
||||
|
||||
func TestNextToken(t *testing.T) {
|
||||
input := `{id:int min(1) max(5) else 404}`
|
||||
|
||||
tests := []struct {
|
||||
expectedType token.TokenType
|
||||
expectedLiteral string
|
||||
}{
|
||||
{token.LBRACE, "{"}, // 0
|
||||
{token.IDENT, "id"}, // 1
|
||||
{token.COLON, ":"}, // 2
|
||||
{token.IDENT, "int"}, // 3
|
||||
{token.IDENT, "min"}, // 4
|
||||
{token.LPAREN, "("}, // 5
|
||||
{token.INT, "1"}, // 6
|
||||
{token.RPAREN, ")"}, // 7
|
||||
{token.IDENT, "max"}, // 8
|
||||
{token.LPAREN, "("}, // 9
|
||||
{token.INT, "5"}, // 10
|
||||
{token.RPAREN, ")"}, // 11
|
||||
{token.ELSE, "else"}, // 12
|
||||
{token.INT, "404"}, // 13
|
||||
{token.RBRACE, "}"}, // 14
|
||||
}
|
||||
|
||||
l := New(input)
|
||||
|
||||
for i, tt := range tests {
|
||||
tok := l.NextToken()
|
||||
|
||||
if tok.Type != tt.expectedType {
|
||||
t.Fatalf("tests[%d] - tokentype wrong. expected=%q, got=%q",
|
||||
i, tt.expectedType, tok.Type)
|
||||
}
|
||||
|
||||
if tok.Literal != tt.expectedLiteral {
|
||||
t.Fatalf("tests[%d] - literal wrong. expected=%q, got=%q",
|
||||
i, tt.expectedLiteral, tok.Literal)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// EMEINA STO:
|
||||
// 30/232 selida apto making a interpeter in Go.
|
||||
// den ekana to skipWhitespaces giati skeftomai
|
||||
// an borei na to xreiastw 9a dw aurio.
|
||||
180
core/router/macro/interpreter/parser/parser.go
Normal file
180
core/router/macro/interpreter/parser/parser.go
Normal file
@@ -0,0 +1,180 @@
|
||||
// Copyright 2017 Gerasimos Maropoulos. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package parser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kataras/iris/core/router/macro/interpreter/ast"
|
||||
"github.com/kataras/iris/core/router/macro/interpreter/lexer"
|
||||
"github.com/kataras/iris/core/router/macro/interpreter/token"
|
||||
)
|
||||
|
||||
func Parse(fullpath string) ([]*ast.ParamStatement, error) {
|
||||
pathParts := strings.SplitN(fullpath, "/", -1)
|
||||
p := new(ParamParser)
|
||||
statements := make([]*ast.ParamStatement, 0)
|
||||
for i, s := range pathParts {
|
||||
if s == "" { // if starts with /
|
||||
continue
|
||||
}
|
||||
|
||||
// if it's not a named path parameter of the new syntax then continue to the next
|
||||
if s[0] != lexer.Begin || s[len(s)-1] != lexer.End {
|
||||
continue
|
||||
}
|
||||
|
||||
p.Reset(s)
|
||||
stmt, err := p.Parse()
|
||||
if err != nil {
|
||||
// exit on first error
|
||||
return nil, err
|
||||
}
|
||||
// if we have param type path but it's not the last path part
|
||||
if stmt.Type == ast.ParamTypePath && i < len(pathParts)-1 {
|
||||
return nil, fmt.Errorf("param type 'path' should be lived only inside the last path segment, but was inside: %s", s)
|
||||
}
|
||||
|
||||
statements = append(statements, stmt)
|
||||
}
|
||||
|
||||
return statements, nil
|
||||
}
|
||||
|
||||
type ParamParser struct {
|
||||
src string
|
||||
errors []string
|
||||
}
|
||||
|
||||
func NewParamParser(src string) *ParamParser {
|
||||
p := new(ParamParser)
|
||||
p.Reset(src)
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *ParamParser) Reset(src string) {
|
||||
p.src = src
|
||||
|
||||
p.errors = []string{}
|
||||
}
|
||||
|
||||
func (p *ParamParser) appendErr(format string, a ...interface{}) {
|
||||
p.errors = append(p.errors, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
const DefaultParamErrorCode = 404
|
||||
const DefaultParamType = ast.ParamTypeString
|
||||
|
||||
func parseParamFuncArg(t token.Token) (a ast.ParamFuncArg, err error) {
|
||||
if t.Type == token.INT {
|
||||
return ast.ParamFuncArgToInt(t.Literal)
|
||||
}
|
||||
return t.Literal, nil
|
||||
}
|
||||
|
||||
func (p ParamParser) Error() error {
|
||||
if len(p.errors) > 0 {
|
||||
return fmt.Errorf(strings.Join(p.errors, "\n"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *ParamParser) Parse() (*ast.ParamStatement, error) {
|
||||
l := lexer.New(p.src)
|
||||
|
||||
stmt := &ast.ParamStatement{
|
||||
ErrorCode: DefaultParamErrorCode,
|
||||
Type: DefaultParamType,
|
||||
Src: p.src,
|
||||
}
|
||||
|
||||
lastParamFunc := ast.ParamFunc{}
|
||||
|
||||
for {
|
||||
t := l.NextToken()
|
||||
if t.Type == token.EOF {
|
||||
if stmt.Name == "" {
|
||||
p.appendErr("[1:] parameter name is missing")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
switch t.Type {
|
||||
case token.LBRACE:
|
||||
// name, alphabetical and _, param names are not allowed to contain any number.
|
||||
nextTok := l.NextToken()
|
||||
stmt.Name = nextTok.Literal
|
||||
case token.COLON:
|
||||
// type
|
||||
nextTok := l.NextToken()
|
||||
paramType := ast.LookupParamType(nextTok.Literal)
|
||||
if paramType == ast.ParamTypeUnExpected {
|
||||
p.appendErr("[%d:%d] unexpected parameter type: %s", t.Start, t.End, nextTok.Literal)
|
||||
}
|
||||
stmt.Type = paramType
|
||||
// param func
|
||||
case token.IDENT:
|
||||
lastParamFunc.Name = t.Literal
|
||||
case token.LPAREN:
|
||||
// param function without arguments ()
|
||||
if l.PeekNextTokenType() == token.RPAREN {
|
||||
// do nothing, just continue to the RPAREN
|
||||
continue
|
||||
}
|
||||
|
||||
argValTok := l.NextDynamicToken() // catch anything from "(" and forward, until ")", because we need to
|
||||
// be able to use regex expression as a macro type's func argument too.
|
||||
argVal, err := parseParamFuncArg(argValTok)
|
||||
if err != nil {
|
||||
p.appendErr("[%d:%d] expected param func argument to be a string or number but got %s", t.Start, t.End, argValTok.Literal)
|
||||
continue
|
||||
}
|
||||
|
||||
// fmt.Printf("argValTok: %#v\n", argValTok)
|
||||
// fmt.Printf("argVal: %#v\n", argVal)
|
||||
lastParamFunc.Args = append(lastParamFunc.Args, argVal)
|
||||
|
||||
case token.COMMA:
|
||||
argValTok := l.NextToken()
|
||||
argVal, err := parseParamFuncArg(argValTok)
|
||||
if err != nil {
|
||||
p.appendErr("[%d:%d] expected param func argument to be a string or number type but got %s", t.Start, t.End, argValTok.Literal)
|
||||
continue
|
||||
}
|
||||
|
||||
lastParamFunc.Args = append(lastParamFunc.Args, argVal)
|
||||
case token.RPAREN:
|
||||
stmt.Funcs = append(stmt.Funcs, lastParamFunc)
|
||||
lastParamFunc = ast.ParamFunc{} // reset
|
||||
case token.ELSE:
|
||||
errCodeTok := l.NextToken()
|
||||
if errCodeTok.Type != token.INT {
|
||||
p.appendErr("[%d:%d] expected error code to be an integer but got %s", t.Start, t.End, errCodeTok.Literal)
|
||||
continue
|
||||
}
|
||||
errCode, err := strconv.Atoi(errCodeTok.Literal)
|
||||
if err != nil {
|
||||
// this is a bug on lexer if throws because we already check for token.INT
|
||||
p.appendErr("[%d:%d] unexpected lexer error while trying to convert error code to an integer, %s", t.Start, t.End, err.Error())
|
||||
continue
|
||||
}
|
||||
stmt.ErrorCode = errCode
|
||||
case token.RBRACE:
|
||||
// check if } but not {
|
||||
if stmt.Name == "" {
|
||||
p.appendErr("[%d:%d] illegal token: }, forgot '{' ?", t.Start, t.End)
|
||||
}
|
||||
break
|
||||
case token.ILLEGAL:
|
||||
p.appendErr("[%d:%d] illegal token: %s", t.Start, t.End, t.Literal)
|
||||
default:
|
||||
p.appendErr("[%d:%d] unexpected token type: %q with value %s", t.Start, t.End, t.Type, t.Literal)
|
||||
}
|
||||
}
|
||||
|
||||
return stmt, p.Error()
|
||||
}
|
||||
258
core/router/macro/interpreter/parser/parser_test.go
Normal file
258
core/router/macro/interpreter/parser/parser_test.go
Normal file
@@ -0,0 +1,258 @@
|
||||
// Copyright 2017 Gerasimos Maropoulos. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package parser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kataras/iris/core/router/macro/interpreter/ast"
|
||||
)
|
||||
|
||||
func TestParseParamError(t *testing.T) {
|
||||
// fail
|
||||
illegalChar := '$'
|
||||
|
||||
input := "{id" + string(illegalChar) + "int range(1,5) else 404}"
|
||||
p := NewParamParser(input)
|
||||
|
||||
_, err := p.Parse()
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("expecting not empty error on input '%s'", input)
|
||||
}
|
||||
|
||||
illIdx := strings.IndexRune(input, illegalChar)
|
||||
expectedErr := fmt.Sprintf("[%d:%d] illegal token: %s", illIdx, illIdx, "$")
|
||||
if got := err.Error(); got != expectedErr {
|
||||
t.Fatalf("expecting error to be '%s' but got: %s", expectedErr, got)
|
||||
}
|
||||
//
|
||||
|
||||
// success
|
||||
input2 := "{id:int range(1,5) else 404}"
|
||||
p.Reset(input2)
|
||||
_, err = p.Parse()
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("expecting empty error on input '%s', but got: %s", input2, err.Error())
|
||||
}
|
||||
//
|
||||
}
|
||||
|
||||
func TestParseParam(t *testing.T) {
|
||||
tests := []struct {
|
||||
valid bool
|
||||
expectedStatement ast.ParamStatement
|
||||
}{
|
||||
{true,
|
||||
ast.ParamStatement{
|
||||
Src: "{id:int min(1) max(5) else 404}",
|
||||
Name: "id",
|
||||
Type: ast.ParamTypeInt,
|
||||
Funcs: []ast.ParamFunc{
|
||||
{
|
||||
Name: "min",
|
||||
Args: []ast.ParamFuncArg{1}},
|
||||
{
|
||||
Name: "max",
|
||||
Args: []ast.ParamFuncArg{5}},
|
||||
},
|
||||
ErrorCode: 404,
|
||||
}}, // 0
|
||||
{true,
|
||||
ast.ParamStatement{
|
||||
Src: "{id:int range(1,5)}",
|
||||
Name: "id",
|
||||
Type: ast.ParamTypeInt,
|
||||
Funcs: []ast.ParamFunc{
|
||||
{
|
||||
Name: "range",
|
||||
Args: []ast.ParamFuncArg{1, 5}},
|
||||
},
|
||||
ErrorCode: 404,
|
||||
}}, // 1
|
||||
{true,
|
||||
ast.ParamStatement{
|
||||
Src: "{file:path contains(.)}",
|
||||
Name: "file",
|
||||
Type: ast.ParamTypePath,
|
||||
Funcs: []ast.ParamFunc{
|
||||
{
|
||||
Name: "contains",
|
||||
Args: []ast.ParamFuncArg{"."}},
|
||||
},
|
||||
ErrorCode: 404,
|
||||
}}, // 2
|
||||
{true,
|
||||
ast.ParamStatement{
|
||||
Src: "{username:alphabetical}",
|
||||
Name: "username",
|
||||
Type: ast.ParamTypeAlphabetical,
|
||||
ErrorCode: 404,
|
||||
}}, // 3
|
||||
{true,
|
||||
ast.ParamStatement{
|
||||
Src: "{myparam}",
|
||||
Name: "myparam",
|
||||
Type: ast.ParamTypeString,
|
||||
ErrorCode: 404,
|
||||
}}, // 4
|
||||
{false,
|
||||
ast.ParamStatement{
|
||||
Src: "{myparam_:thisianunexpected}",
|
||||
Name: "myparam_",
|
||||
Type: ast.ParamTypeUnExpected,
|
||||
ErrorCode: 404,
|
||||
}}, // 5
|
||||
{false, // false because it will give an error of unexpeced token type with value 2
|
||||
ast.ParamStatement{
|
||||
Src: "{myparam2}",
|
||||
Name: "myparam", // expected "myparam" because we don't allow integers to the parameter names.
|
||||
Type: ast.ParamTypeString,
|
||||
ErrorCode: 404,
|
||||
}}, // 6
|
||||
{true,
|
||||
ast.ParamStatement{
|
||||
Src: "{id:int even()}", // test param funcs without any arguments (LPAREN peek for RPAREN)
|
||||
Name: "id",
|
||||
Type: ast.ParamTypeInt,
|
||||
Funcs: []ast.ParamFunc{
|
||||
{
|
||||
Name: "even"},
|
||||
},
|
||||
ErrorCode: 404,
|
||||
}}, // 7
|
||||
|
||||
}
|
||||
var p *ParamParser = new(ParamParser)
|
||||
for i, tt := range tests {
|
||||
p.Reset(tt.expectedStatement.Src)
|
||||
resultStmt, err := p.Parse()
|
||||
|
||||
if tt.valid && err != nil {
|
||||
t.Fatalf("tests[%d] - error %s", i, err.Error())
|
||||
} else if !tt.valid && err == nil {
|
||||
t.Fatalf("tests[%d] - expected to be a failure", i)
|
||||
}
|
||||
|
||||
if resultStmt != nil { // is valid here
|
||||
if !reflect.DeepEqual(tt.expectedStatement, *resultStmt) {
|
||||
t.Fatalf("tests[%d] - wrong statement, expected and result differs. Details:\n%#v\n%#v", i, tt.expectedStatement, *resultStmt)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
path string
|
||||
valid bool
|
||||
expectedStatements []ast.ParamStatement
|
||||
}{
|
||||
{"/api/users/{id:int min(1) max(5) else 404}", true,
|
||||
[]ast.ParamStatement{{
|
||||
Src: "{id:int min(1) max(5) else 404}",
|
||||
Name: "id",
|
||||
Type: ast.ParamTypeInt,
|
||||
Funcs: []ast.ParamFunc{
|
||||
{
|
||||
Name: "min",
|
||||
Args: []ast.ParamFuncArg{1}},
|
||||
{
|
||||
Name: "max",
|
||||
Args: []ast.ParamFuncArg{5}},
|
||||
},
|
||||
ErrorCode: 404,
|
||||
},
|
||||
}}, // 0
|
||||
{"/admin/{id:int range(1,5)}", true,
|
||||
[]ast.ParamStatement{{
|
||||
Src: "{id:int range(1,5)}",
|
||||
Name: "id",
|
||||
Type: ast.ParamTypeInt,
|
||||
Funcs: []ast.ParamFunc{
|
||||
{
|
||||
Name: "range",
|
||||
Args: []ast.ParamFuncArg{1, 5}},
|
||||
},
|
||||
ErrorCode: 404,
|
||||
},
|
||||
}}, // 1
|
||||
{"/files/{file:path contains(.)}", true,
|
||||
[]ast.ParamStatement{{
|
||||
Src: "{file:path contains(.)}",
|
||||
Name: "file",
|
||||
Type: ast.ParamTypePath,
|
||||
Funcs: []ast.ParamFunc{
|
||||
{
|
||||
Name: "contains",
|
||||
Args: []ast.ParamFuncArg{"."}},
|
||||
},
|
||||
ErrorCode: 404,
|
||||
},
|
||||
}}, // 2
|
||||
{"/profile/{username:alphabetical}", true,
|
||||
[]ast.ParamStatement{{
|
||||
Src: "{username:alphabetical}",
|
||||
Name: "username",
|
||||
Type: ast.ParamTypeAlphabetical,
|
||||
ErrorCode: 404,
|
||||
},
|
||||
}}, // 3
|
||||
{"/something/here/{myparam}", true,
|
||||
[]ast.ParamStatement{{
|
||||
Src: "{myparam}",
|
||||
Name: "myparam",
|
||||
Type: ast.ParamTypeString,
|
||||
ErrorCode: 404,
|
||||
},
|
||||
}}, // 4
|
||||
{"/unexpected/{myparam_:thisianunexpected}", false,
|
||||
[]ast.ParamStatement{{
|
||||
Src: "{myparam_:thisianunexpected}",
|
||||
Name: "myparam_",
|
||||
Type: ast.ParamTypeUnExpected,
|
||||
ErrorCode: 404,
|
||||
},
|
||||
}}, // 5
|
||||
{"/p2/{myparam2}", false, // false because it will give an error of unexpeced token type with value 2
|
||||
[]ast.ParamStatement{{
|
||||
Src: "{myparam2}",
|
||||
Name: "myparam", // expected "myparam" because we don't allow integers to the parameter names.
|
||||
Type: ast.ParamTypeString,
|
||||
ErrorCode: 404,
|
||||
},
|
||||
}}, // 6
|
||||
{"/assets/{file:path}/invalid", false, // path should be in the end segment
|
||||
[]ast.ParamStatement{{
|
||||
Src: "{file:path}",
|
||||
Name: "file",
|
||||
Type: ast.ParamTypePath,
|
||||
ErrorCode: 404,
|
||||
},
|
||||
}}, // 7
|
||||
}
|
||||
for i, tt := range tests {
|
||||
statements, err := Parse(tt.path)
|
||||
|
||||
if tt.valid && err != nil {
|
||||
t.Fatalf("tests[%d] - error %s", i, err.Error())
|
||||
} else if !tt.valid && err == nil {
|
||||
t.Fatalf("tests[%d] - expected to be a failure", i)
|
||||
}
|
||||
for j := range statements {
|
||||
for l := range tt.expectedStatements {
|
||||
if !reflect.DeepEqual(tt.expectedStatements[l], *statements[j]) {
|
||||
t.Fatalf("tests[%d] - wrong statements, expected and result differs. Details:\n%#v\n%#v", i, tt.expectedStatements[l], *statements[j])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
53
core/router/macro/interpreter/token/token.go
Normal file
53
core/router/macro/interpreter/token/token.go
Normal file
@@ -0,0 +1,53 @@
|
||||
// Copyright 2017 Gerasimos Maropoulos. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package token
|
||||
|
||||
type TokenType int
|
||||
|
||||
type Token struct {
|
||||
Type TokenType
|
||||
Literal string
|
||||
Start int // including the first char
|
||||
End int // including the last char
|
||||
}
|
||||
|
||||
// /about/{fullname:alphabetical}
|
||||
// /profile/{anySpecialName:string}
|
||||
// {id:int range(1,5) else 404}
|
||||
// /admin/{id:int eq(1) else 402}
|
||||
// /file/{filepath:file else 405}
|
||||
const (
|
||||
EOF = iota // 0
|
||||
ILLEGAL
|
||||
|
||||
// Identifiers + literals
|
||||
LBRACE // {
|
||||
RBRACE // }
|
||||
// PARAM_IDENTIFIER // id
|
||||
COLON // :
|
||||
LPAREN // (
|
||||
RPAREN // )
|
||||
// PARAM_FUNC_ARG // 1
|
||||
COMMA
|
||||
IDENT // string or keyword
|
||||
// Keywords
|
||||
keywords_start
|
||||
ELSE // else
|
||||
keywords_end
|
||||
INT // 42
|
||||
)
|
||||
|
||||
const eof rune = 0
|
||||
|
||||
var keywords = map[string]TokenType{
|
||||
"else": ELSE,
|
||||
}
|
||||
|
||||
func LookupIdent(ident string) TokenType {
|
||||
if tok, ok := keywords[ident]; ok {
|
||||
return tok
|
||||
}
|
||||
return IDENT
|
||||
}
|
||||
Reference in New Issue
Block a user