crimson

package module
v0.0.0-...-6229a51 Latest Latest
Warning

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

Go to latest
Published: May 14, 2022 License: Apache-2.0 Imports: 18 Imported by: 0

README

Crimson

Crimson is a lightweight web framework in Go.

Config

Crimson can read YAML files as config file using the LoadConfig function. The available options and default values are:

server:
  # Server (application) name
  name: Crimson
  # Port number of the server
  port: 8080
  # Background task wait time when shutting down server (in seconds)
  timeout: 60
browser:
  # If open browser automatically after starting server
  open: false
  # Default open page for browser auto open
  page: /
session:
  # Session provider name
  provider: Crimson
  # Name of cookie for session
  cookie: SESSION_ID
  # Session expires time (in seconds)
  timeout: 3600

To config MySQL data source, add the following lines:

db:
  mysql:
    # Database driver name, usually "mysql". If you are using MariaDB, "mariadb" is also available
    driver: driver
    # Your MySQL username
    username: username
    # Your MySQL password
    password: password
    # Your MySQL URL in format of ip_address:port_number
    url: url
    # Database name
    name: name
    # Extra parameters for connecting MySQL, e.g., useSSL=false&charset=utf8
    extra: extra

Usage

An example of starting server:

package main

import (
	"github.com/areszera/crimson"
	"net/http"
)

func main() {
	// Load config file
	crimson.LoadConfig("config.yaml")
	// Config handler for "/" and "/index", GET method is available
	crimson.AddRoute("(/)|(/index)", indexHandler)
	// Config handlers
	crimson.AddRoutes(
		// Config handler for "/login", POST method only
		*crimson.NewRoute("/login", updateHandler, "POST"),
		// Config handler for route begins with "/user/" and end with numbers and letters  
		*crimson.NewRoute("^/user/[0-9a-zA-Z]*$", userHandler, "GET", "POST"),
	)
	// Instantiate server and start
	crimson.NewServer().Start()
	// The Start() above will block the left code
	// Thus, the following code will not be executed until received system interrupt signal")
	// println("Hello, Crimson!")
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	//...
}

func updateHandler(w http.ResponseWriter, r *http.Request) {
	//...
}

func userHandler(w http.ResponseWriter, r *http.Request) {
	//...
}

An example of using session:

package view

import (
	"github.com/areszera/crimson"
	"net/http"
)

var Manager = crimson.NewSessionManager()

func loginHandler(w http.ResponseWriter, r *http.Request) {
	session := Manager.StartSession(w, r)
	if session.Get("info") == nil {
		session.Set("info", "foobar")
	} else {
		//...
	}
}

func logoutHandler(w http.ResponseWriter, r *http.Request) {
	session := Manager.StartSession(w, r)
	if session.Get("info") != nil {
		session.Delete("info")
	} else {
		//...
	}
}

Documentation

Index

Constants

View Source
const (
	// Version is the current version of Crimson
	Version = "1.0"
)

Variables

This section is empty.

Functions

func AddRoute

func AddRoute(pattern string, handler func(http.ResponseWriter, *http.Request), methods ...string)

AddRoute append one new route.

func AddRoutes

func AddRoutes(r ...route)

AddRoutes appends new route(s).

func AddStaticRoute

func AddStaticRoute(prefix, dir string)

AddStaticRoute configures static file server, e.g. css and js files.

func ErrPageHandler

func ErrPageHandler(w http.ResponseWriter, _ *http.Request, status int, info interface{})

ErrPageHandler sets response status code and error page.

func GetBrowserOpenPage

func GetBrowserOpenPage() string

GetBrowserOpenPage returns open page name for browser auto open

func GetMySQLDBName

func GetMySQLDBName() string

func GetMySQLDataSrc

func GetMySQLDataSrc() string

GetMySQLDataSrc returns MySQL data source in format of username:password@url/db?extra

func GetMySQLDriver

func GetMySQLDriver() string

GetMySQLDriver returns MySQL driver name (usually mysql, mariadb is also available for mariadb)

func GetMySQLExtra

func GetMySQLExtra() string

GetMySQLExtra returns MySQL extra configs

func GetMySQLPassword

func GetMySQLPassword() string

GetMySQLPassword returns MySQL password

func GetMySQLUrl

func GetMySQLUrl() string

GetMySQLUrl returns MySQL URL in format of ip_address:port_number

func GetMySQLUsername

func GetMySQLUsername() string

GetMySQLUsername returns MySQL username

func GetServerName

func GetServerName() string

GetServerName returns application name that configured in config.yml or default value

func GetServerPort

func GetServerPort() int

GetServerPort returns port number that configured in config.yml or default value.

func GetServerTimeout

func GetServerTimeout() int64

GetServerTimeout returns server shut down timeout in uint of second that configured in config.yml or default value.

func GetSessionCookieName

func GetSessionCookieName() string

GetSessionCookieName returns cookie name for session that configured in config.yml or default value.

func GetSessionProviderName

func GetSessionProviderName() string

GetSessionProviderName returns session provider name that configured in config.yml or default value.

func GetSessionTimeout

func GetSessionTimeout() int64

GetSessionTimeout returns session maximum life time that configured in config.yml or default value.

func IsBrowserAutoOpen

func IsBrowserAutoOpen() bool

IsBrowserAutoOpen returns if open browser automatically after starting server

func LoadConfig

func LoadConfig(filename string)

LoadConfig reads file to load config. If failed to load, use the default values.

func NewRoute

func NewRoute(pattern string, handler func(http.ResponseWriter, *http.Request), methods ...string) *route

NewRoute creates new route instance. Available methods will be GET if not entered.

func NewServer

func NewServer() *crimsonServer

NewServer creates new server instance.

func OpenInBrowser

func OpenInBrowser()

OpenInBrowser opens http://127.0.0.1:<port><page> in default browser

func OpenUrlInBrowser

func OpenUrlInBrowser(url string)

OpenUrlInBrowser opens URL in default browser

func PrintError

func PrintError(contents ...interface{})

PrintError displays red error in console.

func PrintInfo

func PrintInfo(contents ...interface{})

PrintInfo displays green information in console.

func PrintWarning

func PrintWarning(contents ...interface{})

PrintWarning displays yellow warnings in console.

func SetDefaultErrPageHandler

func SetDefaultErrPageHandler(handler func(w http.ResponseWriter, r *http.Request, status int, info interface{}))

SetDefaultErrPageHandler sets default error page handler.

func SetLogPrintServerName

func SetLogPrintServerName(val bool)

SetLogPrintServerName sets if print server name when print logs

Types

type Session

type Session interface {
	Set(key, value interface{})
	Get(key interface{}) interface{}
	Delete(key interface{})
	SessionID() string
}

Session is an interface with methods of set, get, delete, and get session ID.

type SessionManager

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

SessionManager for managing sessions.

func NewSessionManager

func NewSessionManager() *SessionManager

NewSessionManager creates new instance for SessionManager

func (*SessionManager) DestroySession

func (m *SessionManager) DestroySession(w http.ResponseWriter, r *http.Request)

DestroySession destroys session by making cookie expired.

func (*SessionManager) GC

func (m *SessionManager) GC()

GC collects expired sessions.

func (*SessionManager) StartSession

func (m *SessionManager) StartSession(w http.ResponseWriter, r *http.Request) (session Session)

StartSession starts session according to session ID stored in cookie. If cookie not set or session id is empty, start a new session. Otherwise, use read session by ID.

Jump to

Keyboard shortcuts

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