goapp

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2020 License: Apache-2.0 Imports: 34 Imported by: 3

README

goapp Build Status GoDoc License

The package is used to initialize an application to simply the creation.

Install

$ go get -u github.com/xgfone/goapp

Usage

package main

import (
	"github.com/xgfone/gconf/v4"
	"github.com/xgfone/goapp"
	"github.com/xgfone/gover"
	"github.com/xgfone/ship/v2"
)

// Define some options.
var (
	conf config
	opts = []gconf.Opt{
		gconf.StrOpt("opt1", "help doc"),
		gconf.IntOpt("opt2", "help doc"),
	}
)

type config struct {
	Addr gconf.StringOptField `default:":80" help:"The address to listen to."`
}

func main() {
	// Initialize the app configuration
	goapp.InitApp("app", gover.Text(), &conf, opts)

	// Initialize and start the app router.
	app := goapp.InitRouter()
	app.Route("/path1").GET(ship.OkHandler())
	app.Route("/path2").GET(func(c *ship.Context) error { return c.Text(200, "OK") })
	app.Start(conf.Addr.Get()).Wait()
}

Build the application above by using the script build.sh like this,

$ ./build.sh
$ ./app --help
  --addr string
        The address to listen to. (default ":80")
  --config-file string
        the config file path.
  --logfile string
        The file path of the log. The default is stdout.
  --loglevel string
        The level of the log, such as debug, info (default "info")
  --opt1 string
        help doc
  --opt2 int
        help doc
  --version bool
        Print the version and exit.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Ef     = klog.Ef
	Tracef = klog.Tracef
	Debugf = klog.Debugf
	Infof  = klog.Infof
	Warnf  = klog.Warnf
	Errorf = klog.Errorf
	Printf = klog.Printf
	Panicf = klog.Panicf
	Fatalf = klog.Fatalf
)

Predefine some log functions.

Please refer to https://godoc.org/github.com/xgfone/klog

View Source
var App = InitRouter()

App is the default global router app.

View Source
var DatabaseOpts = []gconf.Opt{
	gconf.StrOpt("connection", "The URL connection to the alarm database, user:password@tcp(127.0.0.1:3306)/db").C(false),
	gconf.IntOpt("maxconnnum", "The maximum number of the connections.").C(false).D(100),
}

DatabaseOpts collects the options of the SQL database.

View Source
var DefaultRuntimeRouteConfig = RuntimeRouteConfig{ShellConfig: DefaultShellConfig}

DefaultRuntimeRouteConfig is the default RuntimeRouteConfig with DefaultShellConfig.

View Source
var DefaultShellConfig = ShellConfig{Shell: "bash", Timeout: time.Minute}

DefaultShellConfig is the default ShellConfig.

View Source
var ErrRouteTableNotImplemented = errors.New("route table has not implemented")

ErrRouteTableNotImplemented is returned when the route table has not implemented.

View Source
var HistogramBuckets = []float64{.005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 1.5, 2}

HistogramBuckets is used to replace the default Histogram buckets.

View Source
var LogOpts = []gconf.Opt{
	gconf.StrOpt("logfile", "The file path of the log. The default is stdout.").As("log_file"),
	gconf.StrOpt("loglevel", "The level of the log, such as debug, info").D("info").As("log_level"),
}

LogOpts collects the options about the log.

Functions

func AddRuntimeRoutes

func AddRuntimeRoutes(app *ship.Ship, config ...RuntimeRouteConfig)

AddRuntimeRoutes adds the runtime routes.

func DisableBuiltinPrometheusCollector

func DisableBuiltinPrometheusCollector()

DisableBuiltinPrometheusCollector removes the collectors that the default prometheus register registers

func GetDefaultGateway added in v0.4.0

func GetDefaultGateway() (gateway net.IP, err error)

GetDefaultGateway returns the default gateway.

func GetDefaultIP added in v0.4.0

func GetDefaultIP() (ip string, err error)

GetDefaultIP returns the default ip.

func InitApp

func InitApp(appName, version string, options ...interface{})

InitApp initializes the application, which is equal to

InitApp2(appName, version, "100M", 100, options...)

func InitApp2 added in v0.4.0

func InitApp2(appName, version, logfilesize string, logfilenum int, options ...interface{})

InitApp2 initializes the application.

  1. Register the log options.
  2. Initialize configuration.
  3. Initialize the logging.

func InitConfig

func InitConfig(app string, options interface{}, version ...string)

InitConfig initliazlies the configuration options.

options may be gconf.Opt, []gconf.Opt, a pointer to the struct variable, or the list of the pointers to the struct variables. For example,

InitConfig("", gconf.StrOpt("optname", "HELP TEXT"))
InitConfig("appname", []gconf.Opt{gconf.StrOpt("optname", "HELP TEXT")})
InitConfig("", []interface{}{structPtr1, structPtr2}, "1.0.0")
InitConfig("", structPtr, "1.0.0")

func InitLogging

func InitLogging(level, filepath string)

InitLogging is equal to InitLogging2(level, filepath, "100M", 100).

func InitLogging2 added in v0.2.0

func InitLogging2(level, filepath, filesize string, filenum int)

InitLogging2 initializes the logging.

If filepath is empty, it will use Stdout as the writer.

func InitRouter

func InitRouter() *ship.Ship

InitRouter returns a new ship router.

func LogPanic

func LogPanic(name ...string)

LogPanic wrapps and logs the panic.

func Unix

func Unix(sec, nsec int64) time.Time

Unix returns a time with unixstamp in UTC location.

Types

type DB

type DB interface {
	Begin() (*sql.Tx, error)
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
	Close() error
	Conn(ctx context.Context) (*sql.Conn, error)
	Driver() driver.Driver
	Exec(query string, args ...interface{}) (sql.Result, error)
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	Ping() error
	PingContext(ctx context.Context) error
	Prepare(query string) (*sql.Stmt, error)
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRow(query string, args ...interface{}) *sql.Row
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
	SetConnMaxLifetime(d time.Duration)
	SetMaxIdleConns(n int)
	SetMaxOpenConns(n int)
	Stats() sql.DBStats
}

DB is an interface to stands for the general sql.DB.

type DBPool

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

DBPool is a read-write DB pool.

func NewDBPool

func NewDBPool() *DBPool

NewDBPool returns a new DB pool.

func (*DBPool) AddDB

func (p *DBPool) AddDB(index int, writer DB, reader ...DB)

AddDB adds a db into the pool.

If reader is nil, the reader DB is the same as writer by default.

Noitce: the index is only used to sort and identify whether two DBs are equal.

func (*DBPool) AddReaderDB

func (p *DBPool) AddReaderDB(index int, reader DB)

AddReaderDB adds a reader db into the pool.

Noitce: the index is only used to sort and identify whether two DBs are equal.

func (*DBPool) GetAllDBs

func (p *DBPool) GetAllDBs() []DBWrapper

GetAllDBs returns all the dbs.

func (*DBPool) GetDB

func (p *DBPool) GetDB(key string) DB

GetDB is short for GetWriterDB.

func (*DBPool) GetReaderDB

func (p *DBPool) GetReaderDB(key string) DB

GetReaderDB returns the reader DB by the key.

If no reader, return the writer.

func (*DBPool) GetWriterDB

func (p *DBPool) GetWriterDB(key string) DB

GetWriterDB returns the writer DB by the key.

If no DB, return nil.

func (*DBPool) SetIndexer

func (p *DBPool) SetIndexer(index func(key string) int)

SetIndexer sets the indexer to get the corresponding DB by the key, that's, it will convert the same key to a constant index forever.

The default indexer only converts the key ending with any character of "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".

type DBWrapper

type DBWrapper struct {
	Index  int
	Writer DB
	Reader DB
}

DBWrapper is a wrapper of the read and write db.

type Handler

type Handler = ship.Handler

Handler is the type alias of ship.Handler.

func ExecuteShell

func ExecuteShell(handle func(ctx *ship.Context, stdout, stderr []byte) error,
	config ...ShellConfig) Handler

ExecuteShell returns a handler to execute a SHELL command or script.

If handle is nil, it will use the default that does nothing and only returns nil.

The body is the command to be executed as JSON like this:

{
    "cmd":     "BASE64_COMMAND",             // Optional
    "script":  "BASE64_SCRIPT_FILE_CONTENT", // Optional
    "shell":   "SHELL_COMMAND",              // Optional
    "timeout": "10s"                         // Optional
}

Notice:

  1. The executed command or script must be encoded by base64.
  2. If shell is given, it will override the Shell in ShellConfig.
  3. If timeout is given, it will override the Timeout in ShellConfig.

The returned handler is very dangerous, and should not be called by the non-trusted callers.

func PrometheusHandler

func PrometheusHandler(gatherer ...prometheus.Gatherer) Handler

PrometheusHandler returns a prometheus handler.

if missing gatherer, it is prometheus.DefaultGatherer.

func Recover

func Recover(next Handler) Handler

Recover is a ship middleware to recover the panic if exists.

type Middleware

type Middleware = ship.Middleware

Middleware is the type alias of ship.Middleware.

func Prometheus

func Prometheus(namespaceAndSubsystem ...string) Middleware

Prometheus returns a middleware to handle the prometheus metrics.

The first argument is the namespace, and the second is the subsystem. Both of them are optional.

type Route added in v0.4.0

type Route struct {
	Dst *net.IPNet
	Src net.IP
	Gw  net.IP
}

Route is the route information.

type Routes added in v0.4.0

type Routes []Route

Routes is a set of Routes.

func GetIPv4Routes added in v0.4.0

func GetIPv4Routes() (Routes, error)

GetIPv4Routes returns the ipv4 routes.

func GetIPv6Routes added in v0.4.0

func GetIPv6Routes() (Routes, error)

GetIPv6Routes returns the ipv4 routes.

func (Routes) DefaultGateway added in v0.4.0

func (rs Routes) DefaultGateway() net.IP

DefaultGateway returns the default gateway. Return nil if not exist.

type RuntimeRouteConfig

type RuntimeRouteConfig struct {
	ShellConfig

	Prefix    string
	IsReady   func() bool
	IsHealthy func() bool
}

RuntimeRouteConfig is used to configure the runtime routes.

type ShellConfig

type ShellConfig struct {
	Shell   string        // The shell name or path, which is "sh" by default.
	Timeout time.Duration // The timeout to execute the shell command.
}

ShellConfig is used to configure the shell execution.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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