spoukfw

package module
Version: v0.0.0-...-a8a1072 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2017 License: MIT Imports: 30 Imported by: 0

README

[go] A simple framework for Golang 1.7 - with new cheat - inject `context` in http.Request, Great Tip.
The project is conditional finished, is not covered by the tests, 
partially tested under load, good performance. As I used httprouter multiplexer.


Documentation

Index

Constants

View Source
const (
	ApplicationJSON                  = "application/json"
	ApplicationJSONCharsetUTF8       = ApplicationJSON + "; " + CharsetUTF8
	ApplicationJavaScript            = "application/javascript"
	ApplicationJavaScriptCharsetUTF8 = ApplicationJavaScript + "; " + CharsetUTF8
	ApplicationXML                   = "application/xml"
	ApplicationXMLCharsetUTF8        = ApplicationXML + "; " + CharsetUTF8
	ApplicationForm                  = "application/x-www-form-urlencoded"
	ApplicationProtobuf              = "application/protobuf"
	ApplicationMsgpack               = "application/msgpack"
	TextHTML                         = "text/html"
	TextHTMLCharsetUTF8              = TextHTML + "; " + CharsetUTF8
	TextPlain                        = "text/plain"
	TextPlainCharsetUTF8             = TextPlain + "; " + CharsetUTF8
	MultipartForm                    = "multipart/form-data"

	CharsetUTF8 = "charset=utf-8"

	AcceptEncoding     = "Accept-Encoding"
	Authorization      = "Authorization"
	ContentDisposition = "Content-Disposition"
	ContentEncoding    = "Content-Encoding"
	ContentLength      = "Content-Length"
	ContentType        = "Content-Type"
	Location           = "Location"
	Upgrade            = "Upgrade"
	Vary               = "Vary"
	WWWAuthenticate    = "WWW-Authenticate"
	XForwardedFor      = "X-Forwarded-For"
	XRealIP            = "X-Real-IP"
)
View Source
const (
	ErrorRenderContent = "\n[spoukrender][content] `%s`\n"
	ErrorCatcherPanic  = "\n[spoukrender][catcherPanic] `%v`\n"
)
View Source
const (
	SPOUKCARRYUPLOAD   = "[spoukuploader][uploadfile][ERROR] %v\n"
	SPOUKCARRYUPLOADOK = "[spoukuploader][uploadfile][OK] `%v`\n"
)
View Source
const (
	ErrorValueNotValidConvert = "Value not valid for converting"
)

Variables

View Source
var (
	//сообщения об ошибках в формах
	ErrorUsername = "Имя пользователя ошибочно"
	ErrorPassword = "Пароль ошибочен"
	ErrorEmail    = "Почтовый адрес ошибочен"

	//`placeholder` описания для формы
	PlaceUsername = "= имя пользователя = "
	PlacePassword = "= пароль ="
	PlaceEmail    = "= почтовый адрес ="

	//ошибки
	ParseErrorInt       = errors.New("[parseform][error] ошибка парсинга `string`->`int64`")
	PTRFormError        = errors.New("[baseform][error] Ошибка, дай мне указатель на структуру для записи")
	PTRFormErrorMethods = errors.New("[baseform][error] Ошибка, отсутствует реализация интерфейса методов для получения данных из формы")
	CSRFErrorValidate   = "CSRF не валидное значение"

	//название стилей для ошибок в формах полей
	ErrorStyleForm   = "has-error"
	SuccessStyleForm = "has-success"

	//сообщения для ошибки в формах при валидации формы
	ErrorMsgFormString   = "- поле не может быть пустым -"
	ErrorMsgFormCheckbox = "- нажмите на чекбокс, если вы не робот -"
	ErrorMsgFormBool     = "- сделайте отметку -"
	ErrorMsgFormSelect   = "- не выбран ни один из элементов -"
)
View Source
var (
	DefaultValues map[string]DefaultForm = map[string]DefaultForm{
		"Name":      DefaultForm{Placeholder: "=введите имя пользователя=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Username":  DefaultForm{Placeholder: "=введите имя пользователя=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Password":  DefaultForm{Placeholder: "=введите пароль =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Email":     DefaultForm{Placeholder: "=введите email =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Port":      DefaultForm{Placeholder: "=порт сервера=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"CatName":   DefaultForm{Placeholder: "=введите название категории=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Title":     DefaultForm{Placeholder: "=введите заголовок =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"MetaKeys":  DefaultForm{Placeholder: "=введите SEO слова =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"MetaDesc":  DefaultForm{Placeholder: "=введите SEO описание-сниппет =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"MetaRobot": DefaultForm{Placeholder: "=введите занчения для SEO robot=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Message":   DefaultForm{Placeholder: "=введите текст сообщения=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Body":      DefaultForm{Placeholder: "=введите тело сообщения =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Link":      DefaultForm{Placeholder: "=введите ссылку-ключ =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"Age":       DefaultForm{Placeholder: "=введите ваш возраст=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},

		"UserInfoUsername": DefaultForm{Placeholder: "=введите имя пользователя=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"UserInfoPassword": DefaultForm{Placeholder: "=введите пароль =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"UserEmail":        DefaultForm{Placeholder: "=введите email =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"CategoryName":     DefaultForm{Placeholder: "=введите название категории=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"PostTitle":        DefaultForm{Placeholder: "=введите заголовок =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"PostBody":         DefaultForm{Placeholder: "=введите тело сообщения =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"PostSeoMetaKeys":  DefaultForm{Placeholder: "=введите SEO слова =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"PostSeoMetaDesc":  DefaultForm{Placeholder: "=введите SEO описание-сниппет =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"PostSeoMetaRobot": DefaultForm{Placeholder: "=введите занчения для SEO robot=", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"TagName":          DefaultForm{Placeholder: "=введите имя метки =", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поле не может быть пустым"},
		"PostCategoryID":   DefaultForm{Placeholder: "", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "значение должно быть выбрано"},
		"PostUserID":       DefaultForm{Placeholder: "", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "значение должно быть выбрано"},
		"Robot":            DefaultForm{Placeholder: "", ErrorClassStyle: "has-error", SuccessClassStyle: "ok", ErrorMsg: "поставьте отметку что вы не робот"},
	}
)
View Source
var (
	ErrorDBSNotReleased = errors.New("[configproxy][error] DBSInterface not released this instanse")
)
View Source
var (
	ErrorSession = "[spouksession][error] `%s`\n"
)
View Source
var (
	Local_filter = map[string]interface{}{
		"count":   strings.Count,
		"split":   strings.Split,
		"title":   strings.Title,
		"lower":   strings.ToLower,
		"totitle": strings.ToTitle,
		"makemap": MakeMap,
		"in":      MapIn,
		"andlist": AndList,
		"upper":   strings.ToUpper,
		"html2": func(value string) template.HTML {
			return template.HTML(fmt.Sprint(value))
		},
	}
)

определение дефолтных значений фильтров и функций

Functions

func AndList

func AndList(listValues ...interface{}) bool

func GetBoolForm

func GetBoolForm(nameElement string, c *echo.Context) bool

func GetPage

func GetPage(c *echo.Context) int

func MakeErrorMessage

func MakeErrorMessage(def, message string) error

externExport

func MakeMap

func MakeMap(value ...string) []string

func MapIn

func MapIn(value interface{}, stock interface{}) bool

---------------------------------------------------------------------------

рандомные полезные функции для шаблонов

---------------------------------------------------------------------------

Types

type CSRFValidate

type CSRFValidate interface {
	Validate() bool
}

интерфейс для csrf валидации

type DBSInterface

type DBSInterface interface {
	WriteConfigDB() error
	ReadConfigFromDB() error
}

---------------------------------------------------------------------------

spoukProxyConfig

---------------------------------------------------------------------------

type DataSO

type DataSO map[string]interface{}

func NewDataSo

func NewDataSo() *DataSO

---------------------------------------------------------------------------

DataSO

---------------------------------------------------------------------------

func (DataSO) Get

func (s DataSO) Get(section, key string) interface{}

func (DataSO) GetUserData

func (s DataSO) GetUserData(key string) interface{}

func (DataSO) Set

func (s DataSO) Set(section, key string, value interface{})

func (DataSO) SetUserData

func (s DataSO) SetUserData(key string, value interface{})

type DefaultForm

type DefaultForm struct {
	ErrorMsg          string
	ErrorClassStyle   string
	SuccessClassStyle string
	SuccessMessage    string
	Placeholder       string
}

структура для дефолтных значений

type FileInfo

type FileInfo struct {
	Name string
	Path string
	Ext  string
	Size uint
}

type FlashMessage

type FlashMessage struct {
	Status  string
	Message interface{}
}

type MailMessage

type MailMessage struct {
	To         string
	From       string
	Message    string
	Subject    string
	FileAttach string `fullpath to file`
	Host       string
	Port       int
	Username   string
	Password   string
}

func (MailMessage) MailSend

func (mail MailMessage) MailSend(message *MailMessage) error

type MethodsForms

type MethodsForms interface {
	GetMultiple(name string) []string
	GetSingle(name string) string
}
	интерфейс для методов получения данных из формы,
 	для полного абстрагирования от всякого говна, типа фреймворков

type Midfunc

type Midfunc func(SpoukHandler) SpoukHandler

type ProxyMapperConfig

type ProxyMapperConfig struct {
	Stock map[string]interface{}
}

type ProxyMapperValue

type ProxyMapperValue struct {
	Name  string
	Value interface{}
}

type SessObj

type SessObj struct {
	Spoukmux   *Spoukmux
	SpoukCarry *SpoukCarry
}

type SpoukCSRF

type SpoukCSRF struct {
	TimeActive time.Duration
	TimeStart  time.Time
	Salt       string
	Key        *uuid.UUID
	ReadyKey   string
	Csrf_form  func() (*string, error)
	Csrf_head  func() (*string, error)
}

func NewSpoukCSRF

func NewSpoukCSRF(minutesActive int, salt string) *SpoukCSRF

func (SpoukCSRF) VerifyToken

func (c SpoukCSRF) VerifyToken(s *SpoukCarry) bool

func (SpoukCSRF) VerifyTokenString

func (c SpoukCSRF) VerifyTokenString(token string) bool

type SpoukCarry

type SpoukCarry struct {
	Spoukmux *Spoukmux
	// contains filtered or unexported fields
}

func (*SpoukCarry) Config

func (m *SpoukCarry) Config() *Spoukconfig

func (*SpoukCarry) Get

func (sr *SpoukCarry) Get(key string) (value interface{})

func (*SpoukCarry) GetCook

func (sr *SpoukCarry) GetCook(nameCook string) *http.Cookie

func (*SpoukCarry) GetCooks

func (sr *SpoukCarry) GetCooks() []*http.Cookie

func (*SpoukCarry) GetForm

func (sr *SpoukCarry) GetForm(key string) string

func (*SpoukCarry) GetFormValue

func (sr *SpoukCarry) GetFormValue(key string) string

func (*SpoukCarry) GetParam

func (sr *SpoukCarry) GetParam(key string) string

func (*SpoukCarry) GetQuery

func (sr *SpoukCarry) GetQuery(key string) string

func (*SpoukCarry) GetQueryAll

func (sr *SpoukCarry) GetQueryAll(key string) url.Values

func (*SpoukCarry) JSON

func (sr *SpoukCarry) JSON(code int, answer interface{}) (err error)

func (*SpoukCarry) JSONB

func (sr *SpoukCarry) JSONB(httpcode int, b []byte) error

func (*SpoukCarry) Params

func (sr *SpoukCarry) Params() *httprouter.Params

func (*SpoukCarry) Path

func (sr *SpoukCarry) Path() (value string)

func (*SpoukCarry) RealPath

func (m *SpoukCarry) RealPath() string

func (*SpoukCarry) Redirect

func (sr *SpoukCarry) Redirect(path string) error

func (*SpoukCarry) Render

func (m *SpoukCarry) Render(name string, data interface{}) error

func (*SpoukCarry) Request

func (sr *SpoukCarry) Request() *http.Request

func (*SpoukCarry) Response

func (sr *SpoukCarry) Response() *http.ResponseWriter

func (*SpoukCarry) Set

func (sr *SpoukCarry) Set(key string, value interface{})

func (*SpoukCarry) SetCook

func (sr *SpoukCarry) SetCook(c http.Cookie)

func (*SpoukCarry) ShowMiddlwaresAndSession

func (s *SpoukCarry) ShowMiddlwaresAndSession()

func (*SpoukCarry) WriteHTML

func (sr *SpoukCarry) WriteHTML(httpcode int, text string) error

type SpoukConfigProxy

type SpoukConfigProxy struct {
	ConfigFromFile interface{}
	CurrentConfig  interface{}
	ConfigFile     string
	StructFile     interface{}
	Mapper         *ProxyMapperConfig
	// contains filtered or unexported fields
}

func NewSpoukProxyConfig

func NewSpoukProxyConfig(fileconfigjson string, structFile interface{}, dbs DBSInterface) (*SpoukConfigProxy, error)

---------------------------------------------------------------------------

SpoukProxyConfig

---------------------------------------------------------------------------

func (*SpoukConfigProxy) ReadConfigFromDB

func (c *SpoukConfigProxy) ReadConfigFromDB() error

func (*SpoukConfigProxy) ShowType

func (c *SpoukConfigProxy) ShowType(s interface{})

func (*SpoukConfigProxy) WriteConfigDB

func (c *SpoukConfigProxy) WriteConfigDB() error

type SpoukConverter

type SpoukConverter struct {
	// contains filtered or unexported fields
}

func NewSpoukConverter

func NewSpoukConverter() *SpoukConverter

func (*SpoukConverter) ConvertHTMLDatetoUnix

func (c *SpoukConverter) ConvertHTMLDatetoUnix(date string) (int64, error)

---------------------------------------------------------------------------

time convert

---------------------------------------------------------------------------

func (*SpoukConverter) ConvertUnixTimeToString

func (c *SpoukConverter) ConvertUnixTimeToString(unixtime int64) string

func (*SpoukConverter) DataLocalToTimeUnix

func (c *SpoukConverter) DataLocalToTimeUnix(datatimeLocal string) int64

convert HTML5Datatime_local(string)->TimeUnix

func (*SpoukConverter) DirectStringtoInt64

func (c *SpoukConverter) DirectStringtoInt64(v string) int64

func (*SpoukConverter) Result

func (c *SpoukConverter) Result() interface{}

---------------------------------------------------------------------------

возвращает результат конвертации

---------------------------------------------------------------------------

func (*SpoukConverter) StrToInt

func (c *SpoukConverter) StrToInt() *SpoukConverter

func (*SpoukConverter) StrToInt64

func (c *SpoukConverter) StrToInt64() *SpoukConverter

func (*SpoukConverter) TimeUnixToDataLocal

func (c *SpoukConverter) TimeUnixToDataLocal(unixtime int64) string

convert timeUnix->HTML5Datatime_local(string)

func (*SpoukConverter) Value

func (c *SpoukConverter) Value(value interface{}) *SpoukConverter

---------------------------------------------------------------------------

инциализация вводным значением

---------------------------------------------------------------------------

type SpoukFlasher

type SpoukFlasher struct {
	sync.RWMutex
	Key   string
	Stock map[string]*FlashMessage
}

func NewSpoukFlasher

func NewSpoukFlasher() *SpoukFlasher

---------------------------------------------------------------------------

functions

---------------------------------------------------------------------------

func (*SpoukFlasher) Get

func (f *SpoukFlasher) Get(section string) *FlashMessage

func (*SpoukFlasher) Set

func (f *SpoukFlasher) Set(status, section string, message interface{})

type SpoukForm

type SpoukForm struct {
	ParseWithInit bool
	Errors        map[string]string
	Class         map[string]string
	Desc          map[string]string
	Stack         map[string]interface{}
	CSRFValidate  CSRFValidate
	MethodsForms  MethodsForms
	DefaultForm   map[string]DefaultForm
}

базовая структура для всех форм

func NewSpoukForm

func NewSpoukForm(defaultForms map[string]DefaultForm, methodsForm MethodsForms, ParseWithInit bool) *SpoukForm

---------------------------------------------------------------------------

создания инстанса + основной функционал

---------------------------------------------------------------------------

func (*SpoukForm) AddForm

func (b *SpoukForm) AddForm(name string, form DefaultForm)

func (*SpoukForm) ConvertBool

func (b *SpoukForm) ConvertBool(name string) bool

func (*SpoukForm) ConvertInt

func (b *SpoukForm) ConvertInt(name string) int64

func (*SpoukForm) ConvertSliceINT64

func (b *SpoukForm) ConvertSliceINT64(name string) []int64

func (*SpoukForm) ConvertString

func (b *SpoukForm) ConvertString(name string) string

func (*SpoukForm) InitForm

func (b *SpoukForm) InitForm(form UserForm)

func (*SpoukForm) ParseFields

func (b *SpoukForm) ParseFields(obj interface{}) *Stocker

func (*SpoukForm) ParseForm

func (b *SpoukForm) ParseForm(obj interface{})

func (*SpoukForm) ResetForm

func (b *SpoukForm) ResetForm()

---------------------------------------------------------------------------

functions

---------------------------------------------------------------------------

func (*SpoukForm) UpdateForm

func (b *SpoukForm) UpdateForm(form UserForm, obj interface{})

func (b *SpoukForm)LoadForm(obj interface{}, form UserForm) {

//загружаю данные из принятой формы с данными в объект по таким же именам
if reflect.ValueOf(obj).Kind() != reflect.Ptr || reflect.ValueOf(form).Kind() != reflect.Ptr {
	log.Fatal(PTRFormError)
}
//получаю стокер со списком филдов объекта из базы данных как правило
stocker := b.ParseFields(obj)
//заполняет форму данными из объекта, используется при обновлении объектов, как пример
mv := reflect.ValueOf(form).Elem()
mt := reflect.TypeOf(form).Elem()
//провожу заполнение
for x := 0; x < mv.NumField(); x++ {
	//получаем имя элемента структуры
	name := mt.Field(x).Name
	//пробую получить элемент с таким же названием из объекта +
	//if v, ok := stocker.Stock[name]; ok {
	//
	//	b.Stack[name] = v
	//}
}

}

func (*SpoukForm) UpdateFormDeep

func (b *SpoukForm) UpdateFormDeep(form interface{}) []StockValue

func (*SpoukForm) ValidateForm

func (b *SpoukForm) ValidateForm(form UserForm) (status bool)

type SpoukHandler

type SpoukHandler func(*SpoukCarry) error

func (SpoukHandler) ServeHTTPSpouker

func (m SpoukHandler) ServeHTTPSpouker(s *SpoukCarry)

func (sr *spoukrouter) SetMethodNotAllowed(h SpoukHandler) {

sr.router.MethodNotAllowed = sr.wrapperforSpoukHandler(h)

} ---------------------------------------------------------------------------

SPOUKHANDLER

---------------------------------------------------------------------------

type SpoukHandlerStock

type SpoukHandlerStock interface {
	StockInit(s *SpoukCarry, args ...interface{})
}

интерфейс для стека обработчиков

type SpoukLogger

type SpoukLogger struct {
	Logging io.Writer
	// contains filtered or unexported fields
}

func NewSpoukLogger

func NewSpoukLogger(subprefix string, logging io.Writer) *SpoukLogger

func (*SpoukLogger) Error

func (s *SpoukLogger) Error(message string)

func (*SpoukLogger) Info

func (s *SpoukLogger) Info(message string)

func (*SpoukLogger) Printf

func (s *SpoukLogger) Printf(format string, v ...interface{})

func (*SpoukLogger) Warning

func (s *SpoukLogger) Warning(message string)

type SpoukMail

type SpoukMail struct {
	MailMessage MailMessage
}

type SpoukMuxRendering

type SpoukMuxRendering interface {
	SpoukRenderIO(name string, data interface{}, resp http.ResponseWriter, reloadTemplate bool) (err error)
	AddUserFilter(name string, f interface{})
	AddFilters(stack map[string]interface{})
	ReloadTemplate()
}

интерфейс для рендера

type SpoukPaginate

type SpoukPaginate struct {
	Result *SpoukPaginateResult
	// contains filtered or unexported fields
}

func NewSpoukPaginate

func NewSpoukPaginate(s *Spoukmux) *SpoukPaginate

func (*SpoukPaginate) PaginateHTML

func (s *SpoukPaginate) PaginateHTML(current_page int, count_on_page int, count_links int, path string, total_len int) string

func (s *SpoukPaginate) Paginate(typeTable interface{}, page int64, path string) (*SpoukPaginateResult) {

countpage := s.spoukmux.config.CountOnPage
countlinks  := s.spoukmux.config.CountLinks
if answer := s.Dbs.Paginate(typeTable ,page, int(countpage)); answer.Status == false {
	return nil
} else {
	links := s.PaginateHTML(int(page), int(countpage), int(countlinks), path, answer.CountTotal)
	return &SpoukPaginateResult{Total:answer.Total,Result:answer.Result,Links:links}
}

}

type SpoukPaginateResult

type SpoukPaginateResult struct {
	Total  interface{}
	Result interface{}
	Links  string
}

type SpoukRender

type SpoukRender struct {
	Temp    *template.Template
	FIlters template.FuncMap
	Debug   bool
	Path    string
	sync.RWMutex
}

рендеринг инстанс

func NewSpoukRender

func NewSpoukRender(path string, debug bool) *SpoukRender

func (*SpoukRender) AddFilters

func (s *SpoukRender) AddFilters(stack map[string]interface{})

func (*SpoukRender) AddUserFilter

func (s *SpoukRender) AddUserFilter(name string, f interface{})

func (*SpoukRender) HTMLTrims

func (s *SpoukRender) HTMLTrims(body []byte) []byte

func (*SpoukRender) ReloadTemplate

func (s *SpoukRender) ReloadTemplate()

func (*SpoukRender) Render

func (s *SpoukRender) Render(w io.Writer, name string, data interface{}) error

func (*SpoukRender) ShowStack

func (s *SpoukRender) ShowStack()

func (*SpoukRender) SpoukRenderIO

func (s *SpoukRender) SpoukRenderIO(name string, data interface{}, w http.ResponseWriter, reloadTemplate bool) (err error)

type SpoukSession

type SpoukSession struct {
	Spoukmux      *Spoukmux
	Paginate      *SpoukPaginate
	Csrf          *SpoukCSRF
	Flasher       *SpoukFlasher
	Mail          *SpoukMail
	Convert       *SpoukConverter
	SessionObject SpoukSessionObject
}

фабрика сессий, с сохранением состояния между реквестами, статичный инстанс

type SpoukSessionObject

type SpoukSessionObject interface {
	NewSpoukSessionObject(s *SpoukSession, c *SpoukCarry) interface{}
	InitSpoukSessionObject(s interface{})
}

---------------------------------------------------------------------------

сессионный динамический объект, интерфейс для него

---------------------------------------------------------------------------

SpoukSessionObject interface {
	NewSpoukSessionObject(spoukcarry *SpoukCarry, mail *SpoukMail, flasher *SpoukFlasher, csrf *SpoukCSRF,
	spoukPaginate *SpoukPaginate, spoukmux *Spoukmux, conver *SpoukConverter, data *DataSO) *SessionObject
	InitSpoukSessionObject()
}

type SpoukTransliter

type SpoukTransliter struct {
	Validate []int
	Replacer []int
	InValid  []int
}

func NewSpoukTransliter

func NewSpoukTransliter() *SpoukTransliter

func (*SpoukTransliter) InSlice

func (s *SpoukTransliter) InSlice(str []int, target int) bool

func (*SpoukTransliter) ShowAscii

func (s *SpoukTransliter) ShowAscii()

func (*SpoukTransliter) TransliterCyr

func (s *SpoukTransliter) TransliterCyr(str string) string

type SpoukUploader

type SpoukUploader struct {
	Stock []FileInfo
}

func NewSpoukUploader

func NewSpoukUploader() *SpoukUploader

func (*SpoukUploader) Upload

func (u *SpoukUploader) Upload(nameForm string, ajax bool, sr *SpoukCarry) error

---------------------------------------------------------------------------

загрузка single/multiple формы без участия сторонних асинхронных методов типа ajax

---------------------------------------------------------------------------

func (*SpoukUploader) UploadSingleAJAX

func (u *SpoukUploader) UploadSingleAJAX(formName string, sr *SpoukCarry) *FileInfo

---------------------------------------------------------------------------

загрузка одиночного файла с участием AJAX

---------------------------------------------------------------------------

type Spoukconfig

type Spoukconfig struct {
	//http timeouts
	HTTPReadTimeout  time.Duration
	HTTPWriteTimeout time.Duration
	//addr
	Address string
	//ssl + no ssl
	HTTP  string
	HTTPS string
	//template
	TemplatePath  string
	TemplateDebug bool
	//session
	UseSession  bool
	SessionTime int64
	//cookies
	CookName string
	//host info
	Hostname string
	//paginate
	CountOnPage int64
	CountLinks  int64
	//csrf
	CSRFActiveMinute int
	CSRFSalt         string
	//Files download path default
	UPLOADFilesPath string
	//---------------------------------------------------------------------------
	//  проксификатор для внешнего файла конфига, реализованного в .json формате
	//---------------------------------------------------------------------------
	ConfigProxy *SpoukConfigProxy
	// contains filtered or unexported fields
}

func NewSpoukconfig

func NewSpoukconfig() *Spoukconfig

func (*Spoukconfig) InjectExternConfigJson

func (s *Spoukconfig) InjectExternConfigJson(fileconfigjson string, structFile interface{}, dbs DBSInterface) error

---------------------------------------------------------------------------

SpoukConfig

---------------------------------------------------------------------------

type Spoukmux

type Spoukmux struct {
	RouteMapper map[string]spoukMapRoute
	// contains filtered or unexported fields
}

func NewSpoukmux

func NewSpoukmux(spcfg *Spoukconfig) *Spoukmux

func (*Spoukmux) AddMiddleware

func (s *Spoukmux) AddMiddleware(mid Midfunc)

func (*Spoukmux) AddUserFilterRender

func (s *Spoukmux) AddUserFilterRender(name string, f interface{})

func (*Spoukmux) AddUserFlitersRender

func (s *Spoukmux) AddUserFlitersRender(userfilters map[string]interface{})

user filter map[commandintemplate]func closure

func (*Spoukmux) Config

func (s *Spoukmux) Config() *Spoukconfig

func (*Spoukmux) Get

func (s *Spoukmux) Get(path string, h SpoukHandler)

func (*Spoukmux) Multi

func (s *Spoukmux) Multi(methods []string, path string, h SpoukHandler)

func (*Spoukmux) Post

func (s *Spoukmux) Post(path string, h SpoukHandler)

func (*Spoukmux) Run

func (s *Spoukmux) Run()

func (*Spoukmux) RunTLS

func (s *Spoukmux) RunTLS(certFile, keyFile string)

func (Spoukmux) ServeHTTP

func (m Spoukmux) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Spoukmux) Session

func (m *Spoukmux) Session() *SpoukSession

func (*Spoukmux) SetMehodNotAllowedHandler

func (s *Spoukmux) SetMehodNotAllowedHandler(h SpoukHandler)

func (*Spoukmux) SetRender

func (m *Spoukmux) SetRender(r SpoukMuxRendering)

func (*Spoukmux) SetSessionObject

func (s *Spoukmux) SetSessionObject(so SpoukSessionObject)

func (*Spoukmux) SetStockHandlerStock

func (m *Spoukmux) SetStockHandlerStock(stock SpoukHandlerStock)

func (*Spoukmux) ShowConfig

func (s *Spoukmux) ShowConfig()

func (*Spoukmux) ShowMiddlewares

func (s *Spoukmux) ShowMiddlewares()

func (*Spoukmux) ShowRoutingMap

func (m *Spoukmux) ShowRoutingMap()

func (*Spoukmux) StaticFiles

func (m *Spoukmux) StaticFiles(realpath, wwwpath string)

func (*Spoukmux) Subroute

func (s *Spoukmux) Subroute(prefix string) *spoukSubdomain

---------------------------------------------------------------------------

testing subroute

---------------------------------------------------------------------------

type StockValue

type StockValue struct {
	Name  string
	Value interface{}
}

type Stocker

type Stocker struct {
	Stock map[string]interface{}
}

func NewStocker

func NewStocker() *Stocker

---------------------------------------------------------------------------

Стокер структура для внутреннего использования внутри либы

---------------------------------------------------------------------------

type UserForm

type UserForm interface {
	Validate(b *SpoukForm, stock ...interface{}) bool
}

интерфейс для юзерских проверок

Directories

Path Synopsis
Package httprouter is a trie based high performance HTTP request router.
Package httprouter is a trie based high performance HTTP request router.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL