Plugging in Plugins Yourself

Is it assumed that this article does not work when developing a custom plugin?Home · caddyserver/caddy Wiki · GitHub does

I get an unknown directive error from a simple caddy file
./_examples/basic/caddyFile:7 - Error during parsing: Unknown directive ‘header2cookie’

:3000 {
    root ./_www
    gzip
    log ../access.log

    header2cookie {
        CookieName  access_token
    }
}

Rest of my source code for reference. Any help is appreciated.

setup.go

package header2cookie

import (
“strconv”

"github.com/caddyserver/caddy"
"github.com/caddyserver/caddy/caddyhttp/httpserver"

)

func init() {
caddy.RegisterPlugin(“header2cookie”, caddy.Plugin{
ServerType: “http”,
Action: setup,
})
}

func setup(c *caddy.Controller) error {

h2c := Header2Cookie{
	CookieName:          "access_token",
	CookieExpireMinutes: 120,
	Expression:          `\s(\w+)$`,
}

cfg := httpserver.GetConfig(c)

for c.Next() { // skip the directive name
	value := c.Val() // use the value

	switch value {
	case "CookieName":
		h2c.CookieName = value
	case "CookieExpireMinutes":
		i, err := strconv.Atoi(value)
		if err == nil {
			h2c.CookieExpireMinutes = i
		}
	}
}

mid := func(next httpserver.Handler) httpserver.Handler {
	h2c.Next = next
	return h2c

}

cfg.AddMiddleware(mid)

return nil

}

header2cookie.go

package header2cookie

import (
	"net/http"

	"regexp"

	"time"

	"github.com/caddyserver/caddy/caddyhttp/httpserver"
)

//Header2Cookie translates authorization header value to cookie value
type Header2Cookie struct {
	Expression          string
	CookieName          string
	CookieExpireMinutes int
	Next                httpserver.Handler
}

func (h Header2Cookie) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {

	auth := r.Header.Get("Authorization")

	//rg, _ := regexp.Compile(`\s(\w+)$`)
	rg, _ := regexp.Compile(h.Expression)

	token := rg.FindString(auth)

	if token != "" {

		cur := time.Now()

		expire := cur.Add(time.Minute * time.Duration(h.CookieExpireMinutes))

		addCookie(w, h.CookieName, token, expire)

	}

	return h.Next.ServeHTTP(w, r)

}

func addCookie(w http.ResponseWriter, name string, value string, expire time.Time) {

	cookie := http.Cookie{

		Name: name,

		Value: value,

		Expires: expire,
	}

	http.SetCookie(w, &cookie)

}

main.go
package main

import (

"github.com/caddyserver/caddy/caddy/caddymain"

_ "github.com/hacdias/caddy-minify"

_ "github.com/qrider/caddy-plugins/header2cookie"

// plug in plugins here, for example:

// _ "import/path/here"

)

func main() {

// optional: disable telemetry

caddymain.EnableTelemetry = false

caddymain.Run()

}

Welcome to the community!

Did you follow the instructions on this page? Home · caddyserver/caddy Wiki · GitHub

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.