gonews

package
v0.0.0-...-3288a16 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2016 License: AGPL-3.0 Imports: 27 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const CsrfSessionKey = "csrf-unique-id"

Variables

View Source
var DefaultContainerOptions = func() func() ContainerOptions {

	connection, connectionErr := sql.Open("sqlite3", "db.sqlite3")
	secret := []byte("some secret key for debugging purposes")
	sessionCookieStore := sessions.NewCookieStore(secret)
	sessionCookieStore.Options = &sessions.Options{
		Path:     "/",
		HttpOnly: true,
		Secure:   true,
		MaxAge:   60 * 60 * 24,
		Domain:   "localhost",
	}

	return func() ContainerOptions {
		options := ContainerOptions{
			Debug:                 false,
			LogLevel:              INFO,
			Title:                 "gonews",
			Environment:           "development",
			Slogan:                "the news site for gophers",
			Description:           "gonews is a site where gophers publish and discuss news about the go language",
			DataSource:            "db.sqlite3",
			Driver:                "sqlite3",
			TemplateDirectory:     "templates",
			TemplateFileExtension: "tpl.html",
			Secret:                string(secret),
			CommentMaxDepth:       5,
			StoriesPerPage:        30,
			CommentsPerPage:       100,
			Session: struct {
				Name         string
				StoreFactory func() (sessions.Store, error)
			}{
				Name: "go-news",
				StoreFactory: func() (sessions.Store, error) {
					return sessionCookieStore, nil
				},
			},
			ConnectionFactory: func() (*sql.DB, error) {
				return connection, connectionErr
			},
		}
		return options
	}
}()

DefaultContainerOptions returns the default ContainerOptions A closure is used to generate the function which allows us to have a few global variables ,like the session store or the db

Functions

func AuthenticatedUserOnlyMiddleware

func AuthenticatedUserOnlyMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

AuthenticatedUserOnlyMiddleware filters out non authenticated users

func AuthorCommentsController

func AuthorCommentsController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

CommentsByAuthorController displays comments by author

func CSRFValidator

func CSRFValidator(field string, value string, csrfProvider CSRFGenerator, action string, errors ValidationError)

CSRFValidator validates a CSRF Token

func EmailValidator

func EmailValidator(field, value string, errors ValidationError)

EmailValidator validates an email

func FaviconMiddleware

func FaviconMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

FaviconMiddleware returns an empty response when favicon.ico requested

func GetApp

func GetApp(appOptions AppOptions) http.Handler

GetApp returns an application ready to be handled by a server

func IsURL

func IsURL(candidate string) bool

IsURL returns true if is url

Example
package main

import (
	"fmt"

	gonews "github.com/mparaiso/gonews/core"
)

func main() {
	for _, url := range []string{
		"https://active-object./introduction.com",
		"https://at.baz.co.uk/foo.com/?&bar=booo",
		"http://baz.com/bar?id=bizz",
		"http://presentation.opex.com/index.html?foobar=biz#baz",
	} {
		fmt.Println(gonews.IsURL(url))

	}

	for _, url := range []string{
		"at.baz.co.uk/foo.com/?&bar=booo",
		"foo.com",
		"foo",
		"biz/baz",
		"something.com/ with space",
	} {
		fmt.Println(gonews.IsURL(url))
	}

}
Output:

true
true
true
true
false
false
false
false
false

func LoadUserStoryAndCommentVotesMiddleware

func LoadUserStoryAndCommentVotesMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

LoadUserStoryAndCommentVotesMiddleware loads votes for current user

func LoggerMiddleware

func LoggerMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

LoggerMiddleware log each request using comman log format

func LoginController

func LoginController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

LoginController displays the login/signup page

func LogoutController

func LogoutController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

LogoutController logs out a user

func MapRowToStruct

func MapRowToStruct(columns []string, scanner Scanner, Struct interface{}, ignoreMissingFields bool) error

MapRowToStruct automatically maps a db row to a struct .

func MapRowsToSliceOfMaps

func MapRowsToSliceOfMaps(scanner RowsScanner, Map *[]map[string]interface{}) error

MapRowsToSliceOfMaps maps db rows to maps the map keys are the column names (or the aliases if defined in the query)

func MapRowsToSliceOfSlices

func MapRowsToSliceOfSlices(scanner RowsScanner, Slices *[][]interface{}) error

MapRowsToSliceOfSlices maps db rows to a slice of slices

func MapRowsToSliceOfStruct

func MapRowsToSliceOfStruct(scanner RowsScanner, sliceOfStructs interface{}, ignoreMissingField bool) error

MapRowsToSliceOfStruct maps db rows to structs

func MatchValidator

func MatchValidator(field1 string, field2 string, value1, value2 interface{}, errors ValidationError)

MatchValidator validates a string by an expected value

func NewCommentsController

func NewCommentsController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

NewCommentsController displays new comments

func NewStoriesController

func NewStoriesController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

NewestStoriesController displays new stories

func NotFoundController

func NotFoundController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

NotFoundController is a standard 404 page

func NotFoundMiddleware

func NotFoundMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

NotFoundMiddleware handles 404 responses

func PatternValidator

func PatternValidator(field, value string, pattern *regexp.Regexp, errors ValidationError)

PatternValidator valides a value according to a regexp pattern

func PostOnlyMiddleware

func PostOnlyMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

PostOnlyMiddleware filters post requests

func RefreshUserMiddleware

func RefreshUserMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

RefreshUserMiddleware keeps the application aware of the current user but does not authenticate or authorize

func RegistrationController

func RegistrationController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

RegistrationController handles user registration

func ReplyController

func ReplyController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

ReplyController handles comment submission

func SessionMiddleware

func SessionMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

SessionMiddleware provide session capabilities TODO change secret key

func StopWatchMiddleware

func StopWatchMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

StopWatchMiddleware logs the request duration

func StoriesByAuthorController

func StoriesByAuthorController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

ThreadListByAuthorIDController displays user's submitted stories

func StoriesByDomainController

func StoriesByDomainController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

ThreadByHostController displays a list of threads sharing the same host

func StoriesByScoreController

func StoriesByScoreController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

ThreadIndexController displays a list of links

func StoryByIDController

func StoryByIDController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

StoryByIDController displays a thread and its comments

func StringMaxLengthValidator

func StringMaxLengthValidator(field, value string, maxlength int, errors ValidationError)

StringMaxLengthValidator validates a string by maximum length

func StringMinLengthValidator

func StringMinLengthValidator(field, value string, minlength int, errors ValidationError)

StringMinLengthValidator validates a string by minimum length

func StringNotEmptyValidator

func StringNotEmptyValidator(field string, value string, errors ValidationError)

StringNotEmptyValidator checks if a string is empty

func SubmitStoryController

func SubmitStoryController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

SubmissionController handles submitted stories

func TemplateMiddleware

func TemplateMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func())

TemplateMiddleware configure the template engine

func URLValidator

func URLValidator(field, value string, errors ValidationError)

URLValidator validates a URL

func UserProfileController

func UserProfileController(c *Container, rw http.ResponseWriter, r *http.Request, next func())

UserShowController displays the user's informations

Types

type Any

type Any interface{}

Any is any value

type AppOptions

type AppOptions struct {
	Migrate bool
	PublicDirectory,

	Environment string
	ContainerOptions
	ContainerFactory func() *Container
}

AppOptions gather all the configuration options

type CSRFGenerator

type CSRFGenerator interface {
	Generate(actionID string) string
	Valid(token, actionID string) bool
}

CSRFGenerator generates and validate csrf tokens

type CSRFGeneratorProvider

type CSRFGeneratorProvider interface {
	// GetCSRF returns the csrf
	GetCSRFGenerator() (CSRFGenerator, error)
	// MustGetCSRF panics on error
	MustGetCSRFGenerator() CSRFGenerator
}

CSRFGeneratorProvider provides a CSRF generator

type Comment

type Comment struct {
	ID       int64
	ParentID int64
	AuthorID int64

	ThreadID     int64
	Content      string
	CommentScore int
	Created      time.Time
	Updated      time.Time

	// virtual fields
	AuthorName  string
	Depth       int
	Children    Comments
	ThreadTitle string
}

Comment is a comment in a thread

func (*Comment) HasChildren

func (c *Comment) HasChildren() bool

HasChildren return true is the comment has child comments

type CommentForm

type CommentForm struct {
	Name     string
	CSRF     string `schema:"comment_csrf"`
	Content  string `schema:"comment_content"`
	Submit   string `schema:"comment_submit"`
	Goto     string `schema:"comment_goto"`
	ParentID int64  `schema:"comment_parent_id"`
	ThreadID int64  `schema:"comment_thread_id"`

	Errors map[string][]string
	// contains filtered or unexported fields
}

CommentForm is a comment form

func (*CommentForm) HandleRequest

func (f *CommentForm) HandleRequest(r *http.Request) error

HandleRequest handle requests

func (*CommentForm) Model

func (f *CommentForm) Model() *Comment

Model return the underlying model

func (*CommentForm) SetModel

func (f *CommentForm) SetModel(model *Comment)

SetModel sets the form model

type CommentFormValidator

type CommentFormValidator struct {
	CSRFGenerator
}

CommentFormValidator validates a comment form

func (*CommentFormValidator) Validate

func (validator *CommentFormValidator) Validate(form *CommentForm) ValidationError

Validate validades a comment form

type CommentRepository

type CommentRepository struct {
	*sql.DB
	Logger LoggerInterface
}

CommentRepository is a repository of comments

func (*CommentRepository) Create

func (repository *CommentRepository) Create(comment *Comment) error

Create creates an new comment

func (*CommentRepository) GetByID

func (repository *CommentRepository) GetByID(id int64) (comment *Comment, err error)

GetByID gets a comment by ID

func (*CommentRepository) GetCommentsByAuthorID

func (repository *CommentRepository) GetCommentsByAuthorID(id int64) (comments Comments, err error)

GetCommentsByAuthorID returns comments by author_id

func (*CommentRepository) GetNewestComments

func (repository *CommentRepository) GetNewestComments() (comments Comments, err error)

GetNewestComments returns comments sorted by date of creation

type CommentVote

type CommentVote struct {
	ID        int64
	CommentID int64
	AuthorID  int64
	Value     int
	Created   time.Time
	Updated   time.Time
}

CommentVote is a comment vote

type CommentVoteRepository

type CommentVoteRepository struct {
	DB     *sql.DB
	Logger LoggerInterface
}

CommentVoteRepository is a repository of comment votes

func (*CommentVoteRepository) GetByUser

func (repository *CommentVoteRepository) GetByUser(user *User) (commentVotes CommentVotes, err error)

GetByUser filters by user

type CommentVotes

type CommentVotes []*CommentVote

CommentVotes is a collection of comment votes

type Comments

type Comments []*Comment

Comments is a collection of comments

func (Comments) At

func (c Comments) At(index int) *Comment

At returns a comment at an index

func (Comments) GetTree

func (c Comments) GetTree() (commentTree []*Comment)

GetTree Builds a tree of comments

func (Comments) Len

func (c Comments) Len() int

Len return the number of comments

type ConcreteValidationError

type ConcreteValidationError map[string][]string

ConcreteValidationError holds errors in a map

func (ConcreteValidationError) Append

func (v ConcreteValidationError) Append(key string, value string)

Append adds an new error to a map

func (ConcreteValidationError) Error

func (v ConcreteValidationError) Error() string

func (ConcreteValidationError) HasErrors

func (v ConcreteValidationError) HasErrors() bool

HasErrors returns true if error exists

type Container

type Container struct {
	ContainerOptions ContainerOptions

	CSRFGeneratorProvider
	TemplateProvider
	SessionProvider
	LoggerProvider
	FormDecoderProvider
	// contains filtered or unexported fields
}

Container contains all the application dependencies

func (*Container) CurrentUser

func (c *Container) CurrentUser() *User

CurrentUser returns an authenticated user

func (Container) Debug

func (c Container) Debug() bool

Debug returns true if debug mode

func (*Container) GetCommentRepository

func (c *Container) GetCommentRepository() (*CommentRepository, error)

GetCommentRepository returns the repository of comments

func (*Container) GetCommentVoteRepository

func (c *Container) GetCommentVoteRepository() (*CommentVoteRepository, error)

GetCommentVoteRepository returns the comment vote repository

func (*Container) GetCommentsPerPage

func (c *Container) GetCommentsPerPage() int

GetCommentsPerPage returns the number of comments per par

func (*Container) GetConnection

func (c *Container) GetConnection() (*sql.DB, error)

GetConnection returns the database connection

func (*Container) GetOptions

func (c *Container) GetOptions() ContainerOptions

GetOptions returns the container's options

func (*Container) GetRoutes

func (c *Container) GetRoutes() *Route

GetRoutes return routes

func (*Container) GetSecret

func (c *Container) GetSecret() string

GetSecret returns the secret key

func (*Container) GetSessionStore

func (c *Container) GetSessionStore() (sessions.Store, error)

GetSessionStore returns a session.Store

func (*Container) GetStoriesPerPage

func (c *Container) GetStoriesPerPage() int

GetStoriesPerPage returns the number of stories per per

func (*Container) GetThreadRepository

func (c *Container) GetThreadRepository() (*ThreadRepository, error)

GetThreadRepository returns a repository for Thread

func (*Container) GetThreadVoteRepository

func (c *Container) GetThreadVoteRepository() (*ThreadVoteRepository, error)

GetThreadVoteRepository returns the thread vote repository

func (*Container) GetUserRepository

func (c *Container) GetUserRepository() (*UserRepository, error)

GetUserRepository returns a repository for User

func (*Container) HTTPError

func (c *Container) HTTPError(rw http.ResponseWriter, r *http.Request, status int, message Any)

HTTPError writes an error to the response

func (*Container) HTTPRedirect

func (c *Container) HTTPRedirect(url string, status int)

HTTPRedirect redirects a request

func (*Container) HasAuthenticatedUser

func (c *Container) HasAuthenticatedUser() bool

HasAuthenticatedUser returns true if a user has been authenticated

func (*Container) MustGetCommentRepository

func (c *Container) MustGetCommentRepository() *CommentRepository

MustGetCommentRepository panics on error

func (*Container) MustGetCommentVoteRepository

func (c *Container) MustGetCommentVoteRepository() *CommentVoteRepository

MustGetCommentVoteRepository can panic on error

func (*Container) MustGetThreadRepository

func (c *Container) MustGetThreadRepository() *ThreadRepository

MustGetThreadRepository panics on error

func (*Container) MustGetThreadVoteRepository

func (c *Container) MustGetThreadVoteRepository() *ThreadVoteRepository

MustGetThreadVoteRepository panics on error

func (*Container) MustGetUserRepository

func (c *Container) MustGetUserRepository() *UserRepository

MustGetUserRepository panics on error or return a repository of User

func (*Container) Request

func (c *Container) Request() *http.Request

Request returns an *http.Request

func (*Container) ResponseWriter

func (c *Container) ResponseWriter() ResponseWriterExtra

ResponseWriter returns the response writer

func (*Container) SetCurrentUser

func (c *Container) SetCurrentUser(u *User)

SetCurrentUser sets the authenticated user

func (*Container) SetDebug

func (c *Container) SetDebug(debug bool)

SetDebug sets debug mode

func (*Container) SetRequest

func (c *Container) SetRequest(request *http.Request)

SetRequest sets the request

func (*Container) SetResponse

func (c *Container) SetResponse(response ResponseWriterExtra)

SetResponse sets the response writer

type ContainerFactory

type ContainerFactory func() *Container

ContainerFactory creates a container

type ContainerOptions

type ContainerOptions struct {
	Environment,
	DataSource,
	Driver,
	Secret,
	Title,
	Slogan,
	Description,
	TemplateDirectory,
	TemplateFileExtension string
	Debug bool
	LogLevel
	// Maximum Depth of a comment thread
	CommentMaxDepth,
	CommentsPerPage,
	StoriesPerPage int
	Session struct {
		Name         string
		StoreFactory func() (sessions.Store, error)
	}
	ConnectionFactory func() (*sql.DB, error)
	LoggerFactory     func() (LoggerInterface, error)
	// contains filtered or unexported fields
}

ContainerOptions are options provided to the container

type DefaultCSRFGenerator

type DefaultCSRFGenerator struct {
	Session SessionWrapper
	Secret  string
}

DefaultCSRFProvider implements CSRFProvider

func (*DefaultCSRFGenerator) Generate

func (d *DefaultCSRFGenerator) Generate(actionID string) string

Generate generates a new token

func (*DefaultCSRFGenerator) Valid

func (d *DefaultCSRFGenerator) Valid(token, actionID string) bool

Valid valides a token

type DefaultCSRFGeneratorProvider

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

DefaultCSRFGeneratorProvider implements CSRFGeneratorProvider

func NewDefaultCSRFGeneratorProvider

func NewDefaultCSRFGeneratorProvider(sessionProvider SessionProvider, secretProvider SecretProvider) *DefaultCSRFGeneratorProvider

NewDefaultCSRFGeneratorProvider returns a new DefaultCSRFGeneratorProvider

func (*DefaultCSRFGeneratorProvider) GetCSRFGenerator

func (provider *DefaultCSRFGeneratorProvider) GetCSRFGenerator() (CSRFGenerator, error)

GetCSRFGenerator returns the csrf generator

func (*DefaultCSRFGeneratorProvider) MustGetCSRFGenerator

func (provider *DefaultCSRFGeneratorProvider) MustGetCSRFGenerator() CSRFGenerator

MustGetCSRFGenerator panics on error

type DefaultFormDecoder

type DefaultFormDecoder struct {
	*schema.Decoder
}

DefaultFormDecoder decode url.Values into a struct

func NewDefaultFormDecoder

func NewDefaultFormDecoder() *DefaultFormDecoder

NewDefaultFormDecoder returns a new DefaultFormDecoder

func (*DefaultFormDecoder) Decode

func (d *DefaultFormDecoder) Decode(destination interface{}, values map[string][]string) error

Decode decodes values into the destination

type DefaultFormDecoderProvider

type DefaultFormDecoderProvider struct {
	FormDecoder
}

DefaultFormDecoderProvider provides a FormDecoder to a container

func NewDefaultFormDecoderProvider

func NewDefaultFormDecoderProvider(formDecoder FormDecoder) *DefaultFormDecoderProvider

NewDefaultFormDecoderProvider returns a new DefaultFormDecoderProvider

func (*DefaultFormDecoderProvider) GetFormDecoder

func (provider *DefaultFormDecoderProvider) GetFormDecoder() FormDecoder

GetFormDecoder returns a FormDecoder

type DefaultLoggerProvider

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

DefaultLoggerProvider provides logging capabilies to a container it implements LoggerProvider

func NewDefaultLoggerProvider

func NewDefaultLoggerProvider(loggerFactory func() (LoggerInterface, error), logLevel LogLevel, debug bool) *DefaultLoggerProvider

NewDefaultLoggerProvider returns a new DefaultLoggerProvider

func (*DefaultLoggerProvider) GetLogger

func (provider *DefaultLoggerProvider) GetLogger() (LoggerInterface, error)

GetLogger gets a logger

func (*DefaultLoggerProvider) MustGetLogger

func (provider *DefaultLoggerProvider) MustGetLogger() LoggerInterface

MustGetLogger panics on error or return a LoggerInterface

type DefaultResponseWriterExtra

type DefaultResponseWriterExtra struct {
	http.ResponseWriter
	Request *http.Request

	sync.Once
	// contains filtered or unexported fields
}

ResponseWriterExtra can notify if a response has been written

func (*DefaultResponseWriterExtra) GetCurrentSize

func (rw *DefaultResponseWriterExtra) GetCurrentSize() int

GetCurrentSize get size written in response

func (*DefaultResponseWriterExtra) HasSession

func (rw *DefaultResponseWriterExtra) HasSession() bool

HasSession returns true if rw has a session

func (*DefaultResponseWriterExtra) IsResponseWritten

func (rw *DefaultResponseWriterExtra) IsResponseWritten() bool

IsResponseWritten returns true if Write has been called

func (*DefaultResponseWriterExtra) Session

Session returns a SessionInterface

func (*DefaultResponseWriterExtra) SetLogger

func (rw *DefaultResponseWriterExtra) SetLogger(logger LoggerInterface)

SetLogger sets the logger

func (*DefaultResponseWriterExtra) SetSession

func (rw *DefaultResponseWriterExtra) SetSession(session SessionWrapper)

SetSession sets the session

func (*DefaultResponseWriterExtra) SetWrittenResponse

func (rw *DefaultResponseWriterExtra) SetWrittenResponse()

SetWrittenResponse returns true if a response has been written

func (*DefaultResponseWriterExtra) Status

func (rw *DefaultResponseWriterExtra) Status() int

Status returns the current status

func (*DefaultResponseWriterExtra) Write

func (rw *DefaultResponseWriterExtra) Write(b []byte) (size int, err error)

Write writes in the response stream

func (*DefaultResponseWriterExtra) WriteHeader

func (rw *DefaultResponseWriterExtra) WriteHeader(status int)

WriteHeader writes the status code

type DefaultSessionProvider

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

DefaultSessionProvider is the default implementation of SessionProvider and provides a session mechanism to a container

func NewDefaultSessionProvider

func NewDefaultSessionProvider(
	name string, sessionStoreProvider SessionStoreProvider, requestProvider RequestProvider, responseWithExtraProvider ResponseWriterExtraProvider) *DefaultSessionProvider

NewDefaultSessionProvider returns a *DefaultSessionProvider

func (*DefaultSessionProvider) GetSession

func (provider *DefaultSessionProvider) GetSession() (SessionWrapper, error)

GetSession returns the session

func (*DefaultSessionProvider) MustGetSession

func (provider *DefaultSessionProvider) MustGetSession() SessionWrapper

MustGetSession panics on error

type DefaultSessionWrapper

type DefaultSessionWrapper struct {
	*sessions.Session
}

Session implementing SessionInterface

func (*DefaultSessionWrapper) Delete

func (s *DefaultSessionWrapper) Delete(key interface{})

func (*DefaultSessionWrapper) Get

func (s *DefaultSessionWrapper) Get(key interface{}) interface{}

Get gets a session value

func (*DefaultSessionWrapper) Has

func (s *DefaultSessionWrapper) Has(key interface{}) bool

Has returns true if key exists

func (*DefaultSessionWrapper) Options

func (s *DefaultSessionWrapper) Options() *sessions.Options

func (*DefaultSessionWrapper) Set

func (s *DefaultSessionWrapper) Set(key interface{}, value interface{})

Set sets a session value

func (*DefaultSessionWrapper) SetOptions

func (s *DefaultSessionWrapper) SetOptions(o *sessions.Options)

func (*DefaultSessionWrapper) Values

func (s *DefaultSessionWrapper) Values() map[interface{}]interface{}

Values return a map of session values

func (*DefaultSessionWrapper) ValuesString

func (s *DefaultSessionWrapper) ValuesString() map[string]interface{}

ValuesString return a map of session values for debugging purposes

type DefaultTemplateEngine

type DefaultTemplateEngine struct {
	*template.Template
	// contains filtered or unexported fields
}

DefaultTemplateEngine implement template provider

func (*DefaultTemplateEngine) Environment

func (t *DefaultTemplateEngine) Environment() Any

Environment returns the environement used in templates. then Environment is passed to every template being rendered

func (*DefaultTemplateEngine) ExecuteTemplate

func (t *DefaultTemplateEngine) ExecuteTemplate(writer io.Writer, name string, data interface{}) error

ExecuteTemplate renders a template

func (*DefaultTemplateEngine) SetEnvironment

func (t *DefaultTemplateEngine) SetEnvironment(env Any)

SetEnvironment sets the environment passed to every rendered template

type DefaultTemplateProvider

type DefaultTemplateProvider struct {
	LoggerProvider
	// contains filtered or unexported fields
}

DefaultTemplateProvider is a default implementation of TemplateProvider. It provides templates to a container.

func NewDefaultTemplateProvider

func NewDefaultTemplateProvider(templateDirectory, templateFileExtension string, isDebug bool, loggerProvider LoggerProvider) *DefaultTemplateProvider

NewDefaultTemplateProvider creates a new DefaultTemplateProvider

func (*DefaultTemplateProvider) GetTemplate

func (provider *DefaultTemplateProvider) GetTemplate() (TemplateEngine, error)

GetTemplate returns *template.Template

func (*DefaultTemplateProvider) MustGetTemplate

func (provider *DefaultTemplateProvider) MustGetTemplate() TemplateEngine

MustGetTemplate panics on error

type Form

type Form interface {
	// HandleRequest deserialize the request body into a form struct
	HandleRequest(r *http.Request) error
}

Form interface is a form

type FormDecoder

type FormDecoder interface {
	Decode(interface{}, map[string][]string) error
}

FormDecoder decode url.Values into a struct

type FormDecoderProvider

type FormDecoderProvider interface {
	GetFormDecoder() FormDecoder
}

FormDecoderProvider provides a FormDecoder to a container

type LogLevel

type LogLevel int8

LogLevel , @see http://www.tutorialspoint.com/log4j/log4j_logging_levels.htm

const (
	ALL LogLevel = iota
	DEBUG
	INFO
	WARN
	ERROR
	FATAL
	OFF
)

type Logger

type Logger struct {
	*log.Logger
	// contains filtered or unexported fields
}

Logger is a logger

func NewDefaultLogger

func NewDefaultLogger(level LogLevel) *Logger

NewDefaultLogger returns a logger using the default log package

func (*Logger) Debug

func (l *Logger) Debug(messages ...interface{})

Debug logs a debugging message

func (*Logger) Error

func (l *Logger) Error(messages ...interface{})

Error logs an error message

func (*Logger) ErrorWithStack

func (l *Logger) ErrorWithStack(messages ...interface{})

ErrorWithStack displays a stack trace

func (*Logger) Info

func (l *Logger) Info(messages ...interface{})

Info logs an info message

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

type LoggerInterface

type LoggerInterface interface {
	Debug(messages ...interface{})
	Info(messages ...interface{})
	Error(messages ...interface{})
	ErrorWithStack(messages ...interface{})
}

LoggerInterface defines a logger

type LoggerProvider

type LoggerProvider interface {
	GetLogger() (LoggerInterface, error)
	MustGetLogger() LoggerInterface
}

LoggerProvider provides a logger to a container

type LoginForm

type LoginForm struct {
	Name     string
	CSRF     string `schema:"login_csrf"`
	Username string `schema:"login_username"`
	Password string `schema:"login_password"`
	Submit   string `schema:"login_submit"`
	Errors   map[string][]string
	// contains filtered or unexported fields
}

LoginForm implements Form

func (*LoginForm) HandleRequest

func (form *LoginForm) HandleRequest(r *http.Request) error

HandleRequest deserialize the request body into a form struct

func (*LoginForm) Model

func (form *LoginForm) Model() *User

Model return the underlying form model

type LoginFormValidator

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

LoginFormValidator is a validator for LoginForm

func (*LoginFormValidator) Validate

func (validator *LoginFormValidator) Validate(form *LoginForm) ValidationError

Validate validates a login form

type Middleware

type Middleware func(*Container, http.ResponseWriter, *http.Request, func())

Middleware is a middleware. It can be transcient or final

type MiddlewareQueue

type MiddlewareQueue struct {
	Middlewares []Middleware
	ContainerFactory
}

MiddlewareQueue is a stack of handlers

Example (First)

ExampleStack_first demonstrates the use of the middleware stack

context := ""
stack := &gonews.MiddlewareQueue{Middlewares: []gonews.Middleware{
	func(c *gonews.Container, rw http.ResponseWriter, r *http.Request, next func()) {
		context += "first middleware-"
		next()
		context += "end"
	},
	func(c *gonews.Container, rw http.ResponseWriter, r *http.Request, next func()) {
		context += "second middleware-"
		next()
	},
}}
middleware := stack.Build()
server := http.NewServeMux()
server.HandleFunc("/", middleware(func(c *gonews.Container, rw http.ResponseWriter, r *http.Request, next func()) {
	context += "main handler-"
	rw.Write([]byte("done"))
}))
testServer := httptest.NewServer(server)
testServer.Config.WriteTimeout = 1000 * time.Millisecond
defer testServer.Close()
url := testServer.URL + "/"

_, err := http.Get(url)
fmt.Println(err)
fmt.Println(context)
Output:

<nil>
first middleware-second middleware-main handler-end

func GetDefaultStack

func GetDefaultStack(factory ContainerFactory) *MiddlewareQueue

GetDefaultStack returns the default middleware stack

func (*MiddlewareQueue) Build

func (s *MiddlewareQueue) Build() func(...Middleware) http.HandlerFunc

Build returns a function that returns a http.HandlerFunc

func (*MiddlewareQueue) Clone

func (s *MiddlewareQueue) Clone() *MiddlewareQueue

Clone clones *Stack

func (*MiddlewareQueue) Push

Push add a new middleware to the stack

func (*MiddlewareQueue) Shift

Shift prepends a new middleware to the stack

type Next

type Next func()

Next is a function that call the next middleware or the handler if all middlewares have been called

type Query

type Query string

Query is an SQL Query

type RegistrationForm

type RegistrationForm struct {
	Name                 string
	CSRF                 string `schema:"registration_csrf"`
	Username             string `schema:"registration_username"`
	Password             string `schema:"registration_password"`
	PasswordConfirmation string `schema:"registration_password_confirmation"`
	Email                string `schema:"registration_email"`
	Submit               string `schema:"registration_submit"`
	Errors               map[string][]string
}

RegistrationForm is a registration form

func (*RegistrationForm) HandleRequest

func (form *RegistrationForm) HandleRequest(r *http.Request) error

HandleRequest populates form values from request or return an error if it can't populate the form

func (*RegistrationForm) Model

func (form *RegistrationForm) Model() *User

Model returns the underlying model

type RegistrationFormValidator

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

RegistrationFormValidator is a RegistrationForm validator

func NewRegistrationFormValidator

func NewRegistrationFormValidator(request *http.Request, csrfProvider CSRFGenerator, userFinder UserFinder) *RegistrationFormValidator

NewRegistrationFormValidator creates an new RegistrationFormValidator

func (*RegistrationFormValidator) Validate

func (validator *RegistrationFormValidator) Validate(form *RegistrationForm) ValidationError

Validate returns nil if no error were found

type RequestProvider

type RequestProvider interface {
	Request() *http.Request
}

RequestProvider provides an *http.Request

type ResponseWriterExtra

type ResponseWriterExtra interface {
	http.ResponseWriter
	IsResponseWritten() bool
	SetSession(SessionWrapper)
	Session() SessionWrapper
	HasSession() bool
	GetCurrentSize() int
	SetLogger(LoggerInterface)
	Status() int
}

ResponseWriterExtraInterface is a response writer enhanced with various apis

type ResponseWriterExtraProvider

type ResponseWriterExtraProvider interface {
	ResponseWriter() ResponseWriterExtra
}

ResponseWriterExtraProvider provides a ResponseWriterExtra

type Role

type Role struct {
	ID   int64
	Name string
}

Role is a role

type RoleRepository

type RoleRepository struct{}

RoleRepository is a repositorCreated y of roles

type Route

type Route struct{}

Route configures URIs

func (Route) AuthorComments

func (Route) AuthorComments() string

func (Route) CastStoryVote

func (Route) CastStoryVote() string

func (Route) Login

func (Route) Login() string

func (Route) Logout

func (Route) Logout() string

func (Route) NewComments

func (Route) NewComments() string

NewComments URI displays comments by age

func (Route) NewStories

func (Route) NewStories() string

NewStories URI displays stories by age

func (Route) Public

func (Route) Public() string

func (Route) Registration

func (Route) Registration() string

func (Route) Reply

func (Route) Reply() string

func (Route) StoriesByAuthor

func (Route) StoriesByAuthor() string

func (Route) StoriesByDomain

func (Route) StoriesByDomain() string

func (Route) StoriesByScore

func (Route) StoriesByScore() string

StoriesByScore is the index

func (Route) StoryByID

func (Route) StoryByID() string

func (Route) SubmitStory

func (Route) SubmitStory() string

func (Route) UserProfile

func (Route) UserProfile() string

type RowsScanner

type RowsScanner interface {
	Close() error
	Columns() ([]string, error)
	Err() error
	Next() bool
	Scan(destination ...interface{}) error
}

type Scanner

type Scanner interface {
	Scan(destination ...interface{}) error
}

Scanner populates destination values or returns an error

type SecretProvider

type SecretProvider interface {
	GetSecret() string
}

SecretProvider provides a secret key

type SessionProvider

type SessionProvider interface {
	GetSession() (SessionWrapper, error)
	MustGetSession() SessionWrapper
}

SessionProvider provides a session mechanism to a container

type SessionStoreProvider

type SessionStoreProvider interface {
	GetSessionStore() (sessions.Store, error)
}

SessionStoreProvider provides a session store to a container

type SessionWrapper

type SessionWrapper interface {
	AddFlash(value interface{}, vars ...string)
	Flashes(vars ...string) []interface{}
	Name() string
	Save(r *http.Request, w http.ResponseWriter) error
	Store() sessions.Store
	Get(interface{}) interface{}
	Set(interface{}, interface{})
	Has(interface{}) bool
	Options() *sessions.Options
	SetOptions(*sessions.Options)
	Values() map[interface{}]interface{}
	ValuesString() map[string]interface{}
	Delete(interface{})
}

SessionInterface was extracted from Session

func NewSession

func NewSession(store sessions.Store, request *http.Request, name string) (SessionWrapper, error)

NewSession create a new session form a store

type SubmissionForm

type SubmissionForm struct {
	Name    string
	CSRF    string `schema:"submission_csrf"`
	Title   string `schema:"submission_title"`
	URL     string `schema:"submission_url"`
	Content string `schema:"submission_content"`
	Submit  string `schema:"submission_submit"`
	Errors  map[string][]string
	// contains filtered or unexported fields
}

SubmissionForm is a submission form

func (*SubmissionForm) HandleRequest

func (form *SubmissionForm) HandleRequest(r *http.Request) error

HandleRequest deserialize the request body into a form struct

func (*SubmissionForm) Model

func (form *SubmissionForm) Model() *Thread

Model return the underlying form model

func (*SubmissionForm) SetModel

func (form *SubmissionForm) SetModel(thread *Thread)

SetModel sets the form model

type SubmissionFormValidator

type SubmissionFormValidator struct {
	CSRFGenerator
}

func (*SubmissionFormValidator) Validate

func (validator *SubmissionFormValidator) Validate(form *SubmissionForm) ValidationError

Validate validates a submission form

type TemplateEngine

type TemplateEngine interface {
	ExecuteTemplate(io.Writer, string, interface{}) error
	Environment() Any
	SetEnvironment(Any)
}

TemplateEngine provides templates

type TemplateEnvironment

type TemplateEnvironment struct {
	FlashMessages map[string][]interface{}
	Request       string
	Description   struct{ Title, Slogan, Description string }
	Configuration struct{ CommentMaxDepth int }
	CurrentUser   *User
	Session       map[string]interface{}
}

TemplateEnvironment is used to store global data common to all templates . it is available as .Environment variable in all templates . Data specific to a controller are available through .Data variable .

type TemplateProvider

type TemplateProvider interface {
	GetTemplate() (TemplateEngine, error)
	MustGetTemplate() TemplateEngine
}

TemplateProvider provides TemplateEngine to a container

type Thread

type Thread struct {
	// db columns
	ID       int64
	Title    string
	URL      string
	Content  string
	Created  time.Time
	Updated  time.Time
	AuthorID int64

	// Author is the author of the thread
	Author *User

	// Comments in the thread
	Comments Comments

	// virtual fields
	AuthorName   string
	CommentCount int
	Score        int
}

Thread is a forum thread

func (Thread) GetURLHost

func (t Thread) GetURLHost() (string, error)

GetURLHost returns the host of the thread url

type ThreadRepository

type ThreadRepository struct {
	DB     *sql.DB
	Logger LoggerInterface
}

ThreadRepository is a repository of threads

func (ThreadRepository) Create

func (repository ThreadRepository) Create(thread *Thread) error

Create creates an thread in the database

func (ThreadRepository) GetByAuthorID

func (repository ThreadRepository) GetByAuthorID(id int64, limit, offset int) (threads Threads, err error)

GetByAuthorID returns threads filtered by AuthorID

func (ThreadRepository) GetByIDWithComments

func (repository ThreadRepository) GetByIDWithComments(id int) (thread *Thread, err error)

GetByIDWithComments gets a threas with its comments

func (ThreadRepository) GetNewest

func (repository ThreadRepository) GetNewest(limit, offset int) (threads Threads, err error)

GetNewest returns threads ordered by age DESC

func (ThreadRepository) GetSortedByScore

func (repository ThreadRepository) GetSortedByScore(limit, offset int) (threads Threads, err error)

GetSortedByScore returns threads ordered by thread vote count

func (ThreadRepository) GetWhereURLLike

func (repository ThreadRepository) GetWhereURLLike(pattern string, limit, offset int) (threads Threads, err error)

GetWhereURLLike returns threads where url like pattern

type ThreadVote

type ThreadVote struct {
	ID       int64
	ThreadID int64
	AuthorID int64
	Score    int64
	Created  time.Time
	Updated  time.Time
}

ThreadVote is a vote for a thread

type ThreadVoteRepository

type ThreadVoteRepository struct {
	DB     *sql.DB
	Logger LoggerInterface
}

ThreadVoteRepository is a repository of thread votes

func (*ThreadVoteRepository) Create

func (repository *ThreadVoteRepository) Create(threadVote *ThreadVote) (i int64, err error)

Create creates a new thread vote

func (*ThreadVoteRepository) GetByUser

func (repository *ThreadVoteRepository) GetByUser(user *User) (threadVotes ThreadVotes, err error)

GetByUser select thread votes bu user

type ThreadVotes

type ThreadVotes []*ThreadVote

ThreadVotes are thread votes

type Threads

type Threads []*Thread

Threads are a collection of stories

func (Threads) GetAuthorIDs

func (threads Threads) GetAuthorIDs() (ids []int64)

GetAuthorIDs return the author's id of each thread

func (Threads) GetAuthorIDsInterface

func (threads Threads) GetAuthorIDsInterface() (ids []interface{})

GetAuthorIDsInterface return the author's id of each thread

type User

type User struct {
	ID       int64
	Username string
	Password string
	Email    string

	Created time.Time
	Updated time.Time
	// Virtual
	Karma int
	ThreadVotes
	CommentVotes
}

User is a forum user

func (*User) Authenticate

func (u *User) Authenticate(unecryptedpassword string) error

Authenticate matches unecryptedpassword with User.Password returns an error if they do not match

func (*User) CanVoteOnComment

func (u *User) CanVoteOnComment(comment *Comment) bool

CanVoteOnComment returns true if user can vote on comment

func (*User) CanVoteOnStory

func (u *User) CanVoteOnStory(thread *Thread) bool

CanVoteOnStory return true if user can vote on story

func (*User) CreateSecurePassword

func (u *User) CreateSecurePassword(unecryptedpassword string) error

CreateSecurePassword generates a secure password from a string and sets User.Password

func (*User) MustCreateSecurePassword

func (u *User) MustCreateSecurePassword(unecryptedpassword string)

MustCreateSecurePassword can panic

type UserFinder

type UserFinder interface {
	GetOneByEmail(string) (*User, error)
	GetOneByUsername(string) (*User, error)
}

UserFinder can find users from a datasource

type UserRepository

type UserRepository struct {
	DB     *sql.DB
	Logger LoggerInterface
}

UserRepository is a repository of users

func (*UserRepository) GetByID

func (repository *UserRepository) GetByID(id int64) (user *User, err error)

GetByID returns a user, an error on error or nil if user not found

func (*UserRepository) GetOneByEmail

func (repository *UserRepository) GetOneByEmail(email string) (user *User, err error)

GetOneByEmail gets one user by his email

func (*UserRepository) GetOneByUsername

func (repository *UserRepository) GetOneByUsername(username string) (user *User, err error)

GetOneByUsername gets one user by his name

func (*UserRepository) Save

func (repository *UserRepository) Save(u *User) error

Save persists a user

type UserRole

type UserRole struct {
	ID     int64
	UserID int
	RoleID int
}

UserRole is a relation between users and roles

type UserValidator

type UserValidator struct {
}

UserValidator is a User validator

func (UserValidator) Validate

func (uv UserValidator) Validate(u *User) ValidationError

Validate validates a user

type ValidationError

type ValidationError interface {
	HasErrors() bool
	Append(key, value string)
	Error() string
}

ValidationError is a validation error

Jump to

Keyboard shortcuts

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