本文整理匯總了Golang中github.com/mholt/caddy.Controller類的典型用法代碼示例。如果您正苦於以下問題:Golang Controller類的具體用法?Golang Controller怎麽用?Golang Controller使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Controller類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ParseRoller
// ParseRoller parses roller contents out of c.
func ParseRoller(c *caddy.Controller) (*LogRoller, error) {
var size, age, keep int
// This is kind of a hack to support nested blocks:
// As we are already in a block: either log or errors,
// c.nesting > 0 but, as soon as c meets a }, it thinks
// the block is over and return false for c.NextBlock.
for c.NextBlock() {
what := c.Val()
if !c.NextArg() {
return nil, c.ArgErr()
}
value := c.Val()
var err error
switch what {
case "size":
size, err = strconv.Atoi(value)
case "age":
age, err = strconv.Atoi(value)
case "keep":
keep, err = strconv.Atoi(value)
}
if err != nil {
return nil, err
}
}
return &LogRoller{
MaxSize: size,
MaxAge: age,
MaxBackups: keep,
LocalTime: true,
}, nil
}
示例2: StringArg
// Assert only one arg and return it
func StringArg(c *caddy.Controller) (string, error) {
args := c.RemainingArgs()
if len(args) != 1 {
return "", c.ArgErr()
}
return args[0], nil
}
示例3: singleArg
func singleArg(c *caddy.Controller, desc string) (string, error) {
args := c.RemainingArgs()
if len(args) != 1 {
return "", c.Errf("%s expects exactly one argument", desc)
}
return args[0], nil
}
示例4: setup
// setup configures a new Git service routine.
func setup(c *caddy.Controller) error {
git, err := parse(c)
if err != nil {
return err
}
// repos configured with webhooks
var hookRepos []*Repo
// functions to execute at startup
var startupFuncs []func() error
// loop through all repos and and start monitoring
for i := range git {
repo := git.Repo(i)
// If a HookUrl is set, we switch to event based pulling.
// Install the url handler
if repo.Hook.URL != "" {
hookRepos = append(hookRepos, repo)
startupFuncs = append(startupFuncs, func() error {
return repo.Pull()
})
} else {
startupFuncs = append(startupFuncs, func() error {
// Start service routine in background
Start(repo)
// Do a pull right away to return error
return repo.Pull()
})
}
}
// ensure the functions are executed once per server block
// for cases like server1.com, server2.com { ... }
c.OncePerServerBlock(func() error {
for i := range startupFuncs {
c.OnStartup(startupFuncs[i])
}
return nil
})
// if there are repo(s) with webhook
// return handler
if len(hookRepos) > 0 {
webhook := &WebHook{Repos: hookRepos}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
webhook.Next = next
return webhook
})
}
return nil
}
示例5: setup
// setup sets up the logging middleware.
func setup(c *caddy.Controller) error {
rules, err := logParse(c)
if err != nil {
return err
}
// Open the log files for writing when the server starts
c.OnStartup(func() error {
for i := 0; i < len(rules); i++ {
var err error
var writer io.Writer
if rules[i].OutputFile == "stdout" {
writer = os.Stdout
} else if rules[i].OutputFile == "stderr" {
writer = os.Stderr
} else if rules[i].OutputFile == "syslog" {
writer, err = gsyslog.NewLogger(gsyslog.LOG_INFO, "LOCAL0", "caddy")
if err != nil {
return err
}
} else {
var file *os.File
file, err = os.OpenFile(rules[i].OutputFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return err
}
if rules[i].Roller != nil {
file.Close()
rules[i].Roller.Filename = rules[i].OutputFile
writer = rules[i].Roller.GetLogWriter()
} else {
rules[i].file = file
writer = file
}
}
rules[i].Log = log.New(writer, "", 0)
}
return nil
})
// When server stops, close any open log files
c.OnShutdown(func() error {
for _, rule := range rules {
if rule.file != nil {
rule.file.Close()
}
}
return nil
})
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
return Logger{Next: next, Rules: rules, ErrorFunc: httpserver.DefaultErrorFunc}
})
return nil
}
示例6: setup
// setup configures a new errors middleware instance.
func setup(c *caddy.Controller) error {
handler, err := errorsParse(c)
if err != nil {
return err
}
// Open the log file for writing when the server starts
c.OnStartup(func() error {
var err error
var writer io.Writer
switch handler.LogFile {
case "visible":
handler.Debug = true
case "stdout":
writer = os.Stdout
case "stderr":
writer = os.Stderr
case "syslog":
writer, err = gsyslog.NewLogger(gsyslog.LOG_ERR, "LOCAL0", "caddy")
if err != nil {
return err
}
default:
if handler.LogFile == "" {
writer = os.Stderr // default
break
}
var file *os.File
file, err = os.OpenFile(handler.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return err
}
if handler.LogRoller != nil {
file.Close()
handler.LogRoller.Filename = handler.LogFile
writer = handler.LogRoller.GetLogWriter()
} else {
writer = file
}
}
handler.Log = log.New(writer, "", 0)
return nil
})
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
handler.Next = next
return handler
})
return nil
}
示例7: GetConfig
// GetConfig gets the SiteConfig that corresponds to c.
// If none exist (should only happen in tests), then a
// new, empty one will be created.
func GetConfig(c *caddy.Controller) *SiteConfig {
ctx := c.Context().(*httpContext)
if cfg, ok := ctx.keysToSiteConfigs[c.Key]; ok {
return cfg
}
// we should only get here during tests because directive
// actions typically skip the server blocks where we make
// the configs
ctx.saveConfig(c.Key, &SiteConfig{Root: Root, TLS: new(caddytls.Config)})
return GetConfig(c)
}
示例8: browseParse
func browseParse(c *caddy.Controller) ([]Config, error) {
var configs []Config
cfg := httpserver.GetConfig(c)
appendCfg := func(bc Config) error {
for _, c := range configs {
if c.PathScope == bc.PathScope {
return fmt.Errorf("duplicate browsing config for %s", c.PathScope)
}
}
configs = append(configs, bc)
return nil
}
for c.Next() {
var bc Config
// First argument is directory to allow browsing; default is site root
if c.NextArg() {
bc.PathScope = c.Val()
} else {
bc.PathScope = "/"
}
bc.Root = http.Dir(cfg.Root)
// Second argument would be the template file to use
var tplText string
if c.NextArg() {
tplBytes, err := ioutil.ReadFile(c.Val())
if err != nil {
return configs, err
}
tplText = string(tplBytes)
} else {
tplText = defaultTemplate
}
// Build the template
tpl, err := template.New("listing").Parse(tplText)
if err != nil {
return configs, err
}
bc.Template = tpl
// Save configuration
err = appendCfg(bc)
if err != nil {
return configs, err
}
}
return configs, nil
}
示例9: setup
// setup used internally by Caddy to set up this middleware
func setup(c *caddy.Controller) error {
mc, err := parse(c)
if err != nil {
return err
}
if c.ServerBlockKeyIndex == 0 {
// only run when the first hostname has been loaded.
if mc.maillog, err = mc.maillog.Init(c.ServerBlockKeys...); err != nil {
return err
}
if err = mc.loadFromEnv(); err != nil {
return err
}
if err = mc.loadPGPKeys(); err != nil {
return err
}
if err = mc.loadTemplate(); err != nil {
return err
}
if err = mc.pingSMTP(); err != nil {
return err
}
c.ServerBlockStorage = newHandler(mc, startMailDaemon(mc))
}
c.OnShutdown(func() error {
if moh, ok := c.ServerBlockStorage.(*handler); ok {
if moh.reqPipe != nil {
close(moh.reqPipe)
moh.reqPipe = nil
}
}
return nil
})
fmt.Printf("%#v\n\n", c)
if moh, ok := c.ServerBlockStorage.(*handler); ok { // moh = mailOutHandler ;-)
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
moh.Next = next
return moh
})
return nil
}
return errors.New("[mailout] Could not create the middleware handler")
}
示例10: extParse
// extParse sets up an instance of extension middleware
// from a middleware controller and returns a list of extensions.
func extParse(c *caddy.Controller) ([]string, error) {
var exts []string
for c.Next() {
// At least one extension is required
if !c.NextArg() {
return exts, c.ArgErr()
}
exts = append(exts, c.Val())
// Tack on any other extensions that may have been listed
exts = append(exts, c.RemainingArgs()...)
}
return exts, nil
}
示例11: registerCallback
// registerCallback registers a callback function to execute by
// using c to parse the directive. It registers the callback
// to be executed using registerFunc.
func registerCallback(c *caddy.Controller, registerFunc func(func() error)) error {
var funcs []func() error
for c.Next() {
args := c.RemainingArgs()
if len(args) == 0 {
return c.ArgErr()
}
nonblock := false
if len(args) > 1 && args[len(args)-1] == "&" {
// Run command in background; non-blocking
nonblock = true
args = args[:len(args)-1]
}
command, args, err := caddy.SplitCommandAndArgs(strings.Join(args, " "))
if err != nil {
return c.Err(err.Error())
}
fn := func() error {
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if nonblock {
log.Printf("[INFO] Nonblocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Start()
}
log.Printf("[INFO] Blocking Command:\"%s %s\"", command, strings.Join(args, " "))
return cmd.Run()
}
funcs = append(funcs, fn)
}
return c.OncePerServerBlock(func() error {
for _, fn := range funcs {
registerFunc(fn)
}
return nil
})
}
示例12: Setup
func Setup(c *caddy.Controller) error {
var m *module
for c.Next() {
if m != nil {
return c.Err("cannot specify realip more than once")
}
m = &module{
Header: "X-Forwarded-For",
}
if err := parse(m, c); err != nil {
return err
}
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
m.next = next
return m
})
return nil
}
示例13: internalParse
func internalParse(c *caddy.Controller) ([]string, error) {
var paths []string
for c.Next() {
if !c.NextArg() {
return paths, c.ArgErr()
}
paths = append(paths, c.Val())
}
return paths, nil
}
示例14: ipfilterParse
// ipfilterParse parses all ipfilter {} blocks to an IPFConfig
func ipfilterParse(c *caddy.Controller) (IPFConfig, error) {
var config IPFConfig
var hasCountryCodes, hasRanges bool
for c.Next() {
path, err := ipfilterParseSingle(&config, c)
if err != nil {
return config, err
}
if len(path.CountryCodes) != 0 {
hasCountryCodes = true
}
if len(path.Nets) != 0 {
hasRanges = true
}
config.Paths = append(config.Paths, path)
}
// having a database is mandatory if you are blocking by country codes.
if hasCountryCodes && config.DBHandler == nil {
return config, c.Err("ipfilter: Database is required to block/allow by country")
}
// needs atleast one of the three.
if !hasCountryCodes && !hasRanges {
return config, c.Err("ipfilter: No IPs or Country codes has been provided")
}
return config, nil
}
示例15: IfMatcherKeyword
// IfMatcherKeyword checks if the next value in the dispenser is a keyword for 'if' config block.
// If true, remaining arguments in the dispinser are cleard to keep the dispenser valid for use.
func IfMatcherKeyword(c *caddy.Controller) bool {
if c.Val() == "if" || c.Val() == "if_op" {
// clear remainig args
c.RemainingArgs()
return true
}
return false
}