cam

package module
v0.5.0-alpha.3 Latest Latest
Warning

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

Go to latest
Published: May 24, 2020 License: Apache-2.0 Imports: 20 Imported by: 0

README

Cam

Http And Socket Framework

GitHub go.mod Go version GitHub tag (latest by date) GitHub last commit GoDoc TODOs

Cam is a personal open source framework. It's goal is not to be lightweight, but to be a large framework of multi-functional integration.

Cam may not be suitable for small projects. It may be more suitable for medium and large-scale projects under multiple modules, at least this is the original intention of its development

Contents

Start with template

1. Clone cam-template from github
git clone --depth=1 https://github.com/go-cam/cam-template.git -b v0.3.0
2. Rename folder to your project name
mv cam-template my-project
3. Update dependency Library
cd my-project
go mod tidy
4. Build and run server module
cd server
go build main.go
./main
5. Check whether it runs successfully

Open the browser and open link: http://127.0.0.1:8800/hello

Easy start

1. Create two file:

go.mod

module app

go 1.14

require (
	github.com/go-cam/cam v0.4.0-alpha.3
)

main.go

package main

import "github.com/go-cam/cam"

func main() {
	cam.RegisterController(&HelloController{})
	cam.RunDefault()
}

type HelloController struct {
	cam.Controller
}

func (ctrl *HelloController) Cam() {
	ctrl.SetResponse([]byte("cam is word."))
}
2. Build and run

build

go build main.go

run

./main

Open the browser and open link: http://127.0.0.1:20200/hello/cam

Template struct:

The document is explained based on this directory
.
|-- .docker                 // docker file
|-- common                  // common module directory
  |-- config                
    |-- app.go              // common module config
  |-- templates
    |-- xorm                // xorm generate orm files's template
      |-- config
      |-- struct.go.tpl
|-- server                  // server module directory
  |-- config
    |-- app.go
    |-- bootstrap.go        // app bootstrap file
  |-- controllers           // controllers directory
    |-- HelloController.go
  |-- main.go               // entry of server module
|-- .gitignore
|-- cam.go                  // command line tools. you can build and execute it
|-- go.mod
|-- go.sum
|-- LICENSE
|-- README.md

Environment support

Examples

.Env file

.env file must be in the same directory as the executable file.

It is recommended to create .env file in this directory: ./server/.env

./server/.env:

DB_USERNAME = root
DB_PASSWORD = 123456

use in code:

username := cam.App.GetEnv("DB_USERNAME") // username = "root"
password := cam.App.GetEnv("DB_PASSWORD") // password = "123456"
fmt.println(username + " " + password) // output: "root 123456"
Upload file

Example:

FileController.go:

import (
	"github.com/go-cam/cam"
	"github.com/go-cam/cam/base/camUtils"
)

type FileController struct {
	cam.HttpController
}

func (ctrl *FileController) Upload() {
	uploadFile := ctrl.GetFile("file")
	if uploadFile == nil {
		cam.App.Fatal("FileController.Upload", "no upload file")
		return
	}

	absFilename := camUtils.File.GetRunPath() + "/runtime/upload/tmp.jpg"
	err := uploadFile.Save(absFilename)
	if err != nil {
		cam.App.Fatal("FileController.Upload", err.Error())
		return
	}

	cam.App.Trace("FileController.Upload", absFilename)
}

Then post file to http://.../file/upload

Validation

Example:

package valid

import (
    "github.com/go-cam/cam"
    "github.com/go-cam/cam/base/camBase"
)

type User struct {
	Email   string
	MyEmail Email
}

type Email string

func (user *User) Rules() []camBase.RuleInterface {
	return []camBase.RuleInterface{
		cam.NewRule([]string{"Email", "MyEmail"}, cam.Rule.Email, cam.Rule.Length(0, 100)),
	}
}

func init() {
    user := new(User)
    user.Email = "123123"
    user.MyEmail = "123@123.com"
    firstErr, _ := cam.Valid(user)
    if firstErr != nil {
        panic(firstErr)
    }
}

Middleware

Support Component: HttpComponent, WebsocketComponent (after v0.4.1-release), SocketComponent (after v0.4.1-release)

add in ComponentConfig

package config

import (
	"github.com/go-cam/cam"
	"github.com/go-cam/cam/base/camBase"
)


func httpServer() camBase.ComponentConfigInterface {
	config := cam.NewHttpConfig(20000)
	config.Register(&controllers.TestController{}) 
	// Add middleware
	config.AddMiddleware("", &AMiddleware{}) // All route will use this Middleware
	return config
}

type AMiddleware struct {
}

func (mid *AMiddleware) Handler(ctx camBase.ContextInterface, next camBase.NextHandler) []byte {
	cam.Debug("AMiddleware", "before")
	res := next()
	cam.Debug("AMiddleware", "after")
	return res
}

Documentation

Index

Constants

View Source
const (
	LogLevelTrace   = camConstants.LevelTrace   // log level: trace
	LogLevelDebug   = camConstants.LevelDebug   // log level: debug
	LogLevelInfo    = camConstants.LevelInfo    // log level: info
	LogLevelWarn    = camConstants.LevelWarn    // log level: warning
	LogLevelError   = camConstants.LevelError   // log level: error
	LogLevelFatal   = camConstants.LevelFatal   // log level: fatal
	LogLevelNone    = camConstants.LevelNone    // none
	LogLevelSuggest = camConstants.LevelSuggest // suggest this level to write file
	LogLevelAll     = camConstants.LevelAll     // all
)

Log

View Source
const (
	ValidModeInterface = camConstants.ModeInterface // Interface mode
	ValidModeTag       = camConstants.ModeTag       // Tag mode
	ValidModeBot       = camConstants.ModeBoth      // Interface and Tag mode
)

Validation

Variables

#################### [START] instance export ####################

Functions

func AddComponent added in v0.4.0

func AddComponent(name string, conf camBase.ComponentConfigInterface)

must run before cam.RunDefault

func Debug added in v0.4.0

func Debug(title, content string)

debug log

func Env added in v0.4.0

func Env(key string) string

get env file values

func Error added in v0.4.0

func Error(title, content string)

error log

func Fatal added in v0.4.0

func Fatal(title, content string)

fatal log

func Info added in v0.4.0

func Info(title, content string)

info log

func NewAppConfig

func NewAppConfig() *camConfig.AppConfig

new Application config

func NewCacheConfig added in v0.3.0

func NewCacheConfig() *camCache.CacheComponentConfig

new cache config

func NewConfig

func NewConfig() *camConfig.Config

new config

func NewConsoleConfig

func NewConsoleConfig() *camConsole.ConsoleComponentConfig

new ConsoleComponent config

func NewDatabaseConfig

func NewDatabaseConfig(driverName string, host string, port string, name string, username string, password string) *camDatabase.DatabaseComponentConfig

new DatabaseComponent config

func NewFileCache added in v0.3.0

func NewFileCache() *camCache.FileCache

new file cache engine

func NewHttpConfig added in v0.3.0

func NewHttpConfig(port uint16) *camHttp.HttpComponentConfig

new ConsoleComponent config

func NewLogConfig added in v0.2.16

func NewLogConfig() *camLog.LogComponentConfig

new log config

func NewMailConfig added in v0.3.0

func NewMailConfig(email string, password string, host string) *camMail.MailComponentConfig

func NewRecover added in v0.3.0

func NewRecover(message string) *camStructs.Recover

func NewRedisCache added in v0.3.0

func NewRedisCache() *camCache.RedisCache

new redis engine

func NewRule added in v0.4.0

func NewRule(fields []string, handlers ...camBase.ValidHandler) *camStructs.Rule

new rule

func NewSocketConfig added in v0.4.0

func NewSocketConfig(port uint16) *camSocket.SocketComponentConfig

new SocketComponentConfig

func NewTemplateCommand added in v0.3.0

func NewTemplateCommand() *template.Command

func NewValidationConfig added in v0.4.0

func NewValidationConfig() *camValidation.ValidationComponentConfig

new ValidationComponentConfig

func NewWebsocketConfig added in v0.3.0

func NewWebsocketConfig(port uint16) *camWebsocket.WebsocketComponentConfig

new WebsocketComponent config

func Param added in v0.4.0

func Param(key string) interface{}

get config param

func RegisterController added in v0.4.0

func RegisterController(ctrl camBase.ControllerInterface)

must run before cam.RunDefault register controller

func RunDefault added in v0.4.0

func RunDefault()

run application

func Trace added in v0.4.0

func Trace(title, content string)

trace log

func Valid added in v0.4.0

func Valid(v interface{}) (firstErr error, errDict map[string][]error)

valid struct

func Warn added in v0.4.0

func Warn(title, content string)

warn log

Types

type Application added in v0.3.0

type Application struct {
	camBase.ApplicationInterface
	// contains filtered or unexported fields
}

framework Application global instance struct define

func NewApplication added in v0.3.0

func NewApplication() *Application

new Application instance

func (*Application) AddComponentAfterRun added in v0.4.0

func (app *Application) AddComponentAfterRun(name string, conf camBase.ComponentConfigInterface) camBase.ComponentInterface

add component after app ran

func (*Application) AddConfig added in v0.3.0

func (app *Application) AddConfig(configI camBase.AppConfigInterface)

Add config. Must be called before calling cam.App.Run (). Merge as much as possible, otherwise overwrite.

config: new config

func (*Application) AddMigration added in v0.3.0

func (app *Application) AddMigration(m camBase.MigrationInterface)

add migration struct

func (*Application) Debug added in v0.3.0

func (app *Application) Debug(title string, content string)

log debug

func (*Application) Error added in v0.3.0

func (app *Application) Error(title string, content string)

log error

func (*Application) Fatal added in v0.3.0

func (app *Application) Fatal(title string, content string)

log fatal

func (*Application) GetCache added in v0.3.0

get cache component

func (*Application) GetComponent added in v0.3.0

Overwrite: Try to get instance using struct type

func (*Application) GetComponentByName added in v0.3.0

func (app *Application) GetComponentByName(name string) camBase.ComponentInterface

Overwrite: Try to get component instance by name. The name is define in config

func (*Application) GetDB added in v0.3.0

get default db component

func (*Application) GetEvn added in v0.3.0

func (app *Application) GetEvn(key string) string

get one .evn file values

func (*Application) GetMail added in v0.3.0

get mail component

func (*Application) GetMigrateDict added in v0.3.0

func (app *Application) GetMigrateDict() map[string]camBase.MigrationInterface

func (*Application) GetParam added in v0.3.0

func (app *Application) GetParam(key string) interface{}

get value form app.config.Params.

func (*Application) Info added in v0.3.0

func (app *Application) Info(title string, content string)

log info

func (*Application) Run added in v0.3.0

func (app *Application) Run()

run Application

func (*Application) Stop added in v0.3.0

func (app *Application) Stop()

stop Application

func (*Application) Trace added in v0.3.0

func (app *Application) Trace(title string, content string)

log trace

func (*Application) Valid added in v0.4.0

func (app *Application) Valid(v interface{}) (firstErr error, errDict map[string][]error)

valid struct

func (*Application) Warn added in v0.3.0

func (app *Application) Warn(title string, content string)

log warning

type ConstantController added in v0.3.0

type ConstantController struct {
	camConsole.ConsoleController
}

type Context added in v0.3.0

type Context struct {
	camContext.Context
}

type Controller added in v0.3.0

type Controller struct {
	camRouter.Controller
}

type ControllerAction added in v0.3.0

type ControllerAction struct {
	camRouter.ControllerAction
}

type HttpController added in v0.3.0

type HttpController struct {
	camHttp.HttpController
}

type MiddlewareInterface added in v0.4.1

type MiddlewareInterface interface {
	camBase.MiddlewareInterface
}

type ValidInterface added in v0.4.0

type ValidInterface interface {
	camBase.ValidInterface
}

Directories

Path Synopsis
base
camMail
From: https://github.com/jordan-wright/email Datetime: 2020-03-09 17:28:00 From: https://github.com/jordan-wright/email Datetime: 2020-03-09 17:28:00
From: https://github.com/jordan-wright/email Datetime: 2020-03-09 17:28:00 From: https://github.com/jordan-wright/email Datetime: 2020-03-09 17:28:00

Jump to

Keyboard shortcuts

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