iska

package module
v0.0.0-...-5508c2e Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2022 License: BSD-3-Clause Imports: 19 Imported by: 0

README

iska

A web Framework Go

INSTALL

With a correctly configured...

go get -u github.com/ethodomingues/iska

A simple example

package main

import (
	"fmt"

	"github.com/ethodomingues/iska"
)

func main() {
	app := iska.NewApp(nil)

	app.Get("/", Hello, "hello", nil)
	app.Get("/{name}", DinamicHello, "dinamicHello", nil)
	app.Get("/{name:string}/{id:int}", DinamicHello, "dinamicHello", nil)

	route := &iska.Route{
		Url:     "/with-schema",
		Name:    "useSchema",
		Func:    WithoutSchema,
		Methods: []string{"GET"},
		HandlerMethods: map[string]*iska.Handler{
			// It's not mandatory
			// but it's pretty cool.
			"POST": {
				Func:          WithSchema,
				RequestSchema: &User{},
			},
		},
	}
	app.AddRoute(route)

	app.Listen()
}

func Hello(w *iska.Response, r *iska.Request) {
	w.JSON(200, map[string]string{"Hello": "World"})
}

func DinamicHello(w *iska.Response, r *iska.Request) {
	name := r.Args["name"]
	id := r.Args.Get("id", "")
	if id != "" {
		// do something...
	}
	w.HTML(200, "<h1>Hello, "+name+"!</h1>")

}

func WithSchema(w *iska.Response, r *iska.Request) {
	user := r.Schema.(User)
	// do something...
	w.JSON(201, user)
}
func WithoutSchema(w *iska.Response, r *iska.Request) {
	// do something...
	fmt.Fprint(w.Body, "Any text") // this gets 'Content-Type: text/plain' by default
}

type User struct {
	Name string `iska:"in:body"`
	Age  int    `iska:"in:body, required:false"`
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnmatch        = errors.New("ErrUnMatch")
	ErrMethodMismatch = errors.New("ErrMethodMismatch")
)

Functions

func GetFuncName

func GetFuncName(f interface{}) string

func NewReqSchema

func NewReqSchema(schema any) *reqSchema

func Ternary

func Ternary(cond bool, trueValue any, defaultValue any) any

func ToTitle

func ToTitle(str string) string

Types

type App

type App struct {
	*Router                             // main router
	*Config                             // settings
	ErrorHandler map[string]HandlerFunc // map[statusCode]func
	// contains filtered or unexported fields
}

func NewApp

func NewApp(cfg map[string]interface{}) *App

func (*App) AddRouter

func (app *App) AddRouter(r *Router)

register a Router in the main App

func (*App) Listen

func (app *App) Listen(addr ...string)

Parse routes, routers config e start a Listener

func (*App) NewSecureSession

func (app *App) NewSecureSession() *SecureSession

func (*App) ServeHTTP

func (app *App) ServeHTTP(wr http.ResponseWriter, rq *http.Request)

match the endpoint and Parse the request, response...

func (*App) ShowRoutes

func (app *App) ShowRoutes()

func (*App) UrlFor

func (app *App) UrlFor(name string, external bool, options ...string) string

type Auth

type Auth struct {
	Username string
	Password string
}

type CORS

type CORS struct {
	Max_Age           string   // <delta-seconds>
	Expose_Headers    string   // X-My-Custom-Header, X-Another-Custom-Header
	Allow_Origin      string   // <origin> | *
	Allow_Methods     []string // <method>[, <method>]*
	Allow_Headers     []string // <field-name>[, <field-name>]*
	Allow_Credentials bool
}

func NewCORS

func NewCORS(cfg map[string]string) *CORS

type Config

type Config struct {

	// Environment Settings
	Env   string // default: production
	Debug bool   // default: production

	// app.Router Settings
	Host      string // default: ""
	SecretKey string // default: "" ( necessario para o uso do Session )

	// Static Files Settings
	StaticFolder  string // default: "/front/assets"
	StaticUrlPath string // default: "/assets"

	// Session Settings
	CookiePath         string        // default: "/"
	CookieDomain       string        // default: ""
	CookieSecure       bool          // default: false
	CookieHttpOnly     bool          // default: true
	RefreshEachRequest bool          // default: true
	CookieExpires      time.Duration // default: default  1 hour
	CookiePermanent    time.Duration // default: default  31 days
	CookieSameSite     http.SameSite // default: http.http.SameSiteDefaultMode
	SessionCookieName  string        // default: "session"
}

func (*Config) Update

func (c *Config) Update(cfg map[string]interface{})

type File

type File struct {
	Header        *multipart.FileHeader
	Buffer        *bytes.Buffer
	Size          int64
	Filename      string
	ContentType   string
	ContentLength int
}

func NewFile

func NewFile(fh *multipart.FileHeader) *File

type HandlerFunc

type HandlerFunc func(w *Response, r *Request)

type Headers

type Headers map[string][]string

func (*Headers) Add

func (h *Headers) Add(key string, values ...string)

func (*Headers) Get

func (h *Headers) Get(name string) []string

func (*Headers) Set

func (h *Headers) Set(key string, values ...string)

func (*Headers) ToString

func (h *Headers) ToString() string

type MapSA

type MapSA map[string]any

func (MapSA) Get

func (m MapSA) Get(key string, _default any) any

type MapSS

type MapSS map[string]string

func (MapSS) Get

func (m MapSS) Get(key string, _default any) any

type Methods

type Methods map[string]*MthHandler

func NewMethods

func NewMethods(mts map[string]HandlerFunc) Methods

type MthHandler

type MthHandler struct {
	CORS           *CORS
	Func           HandlerFunc
	RequestSchema  any
	ResponseSchema ResponseSchema
	// contains filtered or unexported fields
}

type Request

type Request struct {
	MatchInfo *RouteMatch

	// Request Parsed
	G       MapSA              // Global Variable
	App     *App               // the main app
	Args    MapSS              // url variables
	Auth    *Auth              // Auth headers parsed
	Form    MapSS              // form parsed in map[string]string
	Files   map[string][]*File // map of formData parsed in Files ( if exists )
	Session Session            // the Sessions of current user

	// Native Request
	Cookies     []*http.Cookie // []*http.Cookie
	ContentType string         // alias for http.Request.Headers.Get("Content-Type")
	Method      string         // GET | POST | PUT ...
	URL         *url_pkg.URL
	Header      http.Header
	Host        string
	RemoteAddr  string
	RequestURI  string
	Schema      any
	// contains filtered or unexported fields
}

func NewRequest

func NewRequest(app *App, rq *http.Request) *Request

func (*Request) GetFile

func (r *Request) GetFile(filename string) *File

func (*Request) UrlFor

func (r *Request) UrlFor(name string, external bool, options ...string) string

type Response

type Response struct {
	Body       *bytes.Buffer
	Headers    *Headers
	StatusCode int
}

func NewResponse

func NewResponse() *Response

func (*Response) Abort

func (w *Response) Abort(body any, code int, headers map[string]string)

func (*Response) BadRequest

func (w *Response) BadRequest()

func (*Response) HTML

func (w *Response) HTML(code int, body interface{})

func (*Response) HttpError

func (w *Response) HttpError(code int)

func (*Response) InternalServerError

func (w *Response) InternalServerError()

func (*Response) JSON

func (w *Response) JSON(code int, body interface{})

func (*Response) NotFound

func (w *Response) NotFound()

func (*Response) Redirect

func (w *Response) Redirect(url_location string)

func (*Response) TEXT

func (w *Response) TEXT(code int, body interface{})

type ResponseSchema

type ResponseSchema map[string]any

type Route

type Route struct {
	Url            string                 // "/foo/bar/{foo:int}/{bar}"
	Name           string                 // "FooBar"
	Func           HandlerFunc            // func(w *Response, r *Request){}
	Methods        []string               // ["GET", "POST", "DELETE"]
	HandlerMethods map[string]*MthHandler //

	CORS           *CORS          // iska.CORS{}
	RequestSchema  any            // any{}
	ResponseSchema ResponseSchema // map[string]any{200:{field:"foo",Field2: 1, Field3:Obj{...} }}
	// contains filtered or unexported fields
}

type RouteMatch

type RouteMatch struct {
	Route    *Route
	Router   *Router
	HttpVerb *MthHandler

	MatchErr error
}

type Router

type Router struct {
	CORS      *CORS
	Name      string
	UrlPrefix string
	Subdomain string

	AuthFunc func(*Response, *Request) (string, string) // before each request, for parse authorization headers
	// contains filtered or unexported fields
}

func (*Router) AddNewRoute

func (r *Router) AddNewRoute(url string, f HandlerFunc, name string, options map[string]interface{})

func (*Router) AddRoute

func (r *Router) AddRoute(route *Route)

func (*Router) AfterRequest

func (r *Router) AfterRequest(f HandlerFunc)

is execute after each request, if no raise a error

func (*Router) BeforeRequest

func (r *Router) BeforeRequest(f HandlerFunc)

is execute before each request

func (*Router) Connect

func (r *Router) Connect(url string, f HandlerFunc, name string, options map[string]any)

func (*Router) Delete

func (r *Router) Delete(url string, f HandlerFunc, name string, options map[string]any)

func (*Router) Get

func (r *Router) Get(url string, f HandlerFunc, name string, options map[string]any)

func (*Router) Head

func (r *Router) Head(url string, f HandlerFunc, name string, options map[string]any)

func (*Router) Options

func (r *Router) Options(url string, f HandlerFunc, name string, options map[string]any)

func (*Router) Patch

func (r *Router) Patch(url string, f HandlerFunc, name string, options map[string]any)

func (*Router) Post

func (r *Router) Post(url string, f HandlerFunc, name string, options map[string]any)

func (*Router) Put

func (r *Router) Put(url string, f HandlerFunc, name string, options map[string]any)

func (*Router) TeardownRequest

func (r *Router) TeardownRequest(f HandlerFunc)

is execute after dispache request ( no has effect in the request)

func (*Router) Trace

func (r *Router) Trace(url string, f HandlerFunc, name string, options map[string]any)

type Schema

type Schema any

type SecureSession

type SecureSession struct {
	*http.Cookie
	// contains filtered or unexported fields
}

func (*SecureSession) Save

func (s *SecureSession) Save(secret string)

func (*SecureSession) String

func (s *SecureSession) String() ([]byte, error)

type Session

type Session struct {
	Permanent bool
	// contains filtered or unexported fields
}

func (*Session) Delete

func (s *Session) Delete(key string) any

func (*Session) Get

func (s *Session) Get(key string) any

func (*Session) Set

func (s *Session) Set(key string, value any)

type SwaggerField

type SwaggerField struct {
	In          string ``                  // default: query
	Name        string ``                  // default: struct.FieldName
	Type        string ``                  // default: struct.FieldName.Type
	Format      string `json:",omitempty"` // default: ""
	Required    bool   ``                  // default: true
	Description string `json:",omitempty"` // default: ""
}

type SwaggerRoute

type SwaggerRoute struct{}

type SwaggerRouter

type SwaggerRouter struct{}

Jump to

Keyboard shortcuts

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