https://github.com/abiosoft/hello-caddy
Sample external middleware for Caddy
https://github.com/abiosoft/hello-caddy
Last synced: about 1 year ago
JSON representation
Sample external middleware for Caddy
- Host: GitHub
- URL: https://github.com/abiosoft/hello-caddy
- Owner: abiosoft
- License: mit
- Created: 2015-06-21T06:24:48.000Z (almost 11 years ago)
- Default Branch: master
- Last Pushed: 2016-03-26T04:38:39.000Z (about 10 years ago)
- Last Synced: 2025-03-17T05:17:23.155Z (over 1 year ago)
- Language: Go
- Size: 8.79 KB
- Stars: 4
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# hello
Sample add-on for [Caddy](http://caddyserver.com).
## Depreciated
Use the [caddydev](https://github.com/caddyserver/caddydev#create-a-skeleton-add-on) tool to generate skeleton app instead. More [here](https://github.com/caddyserver/caddydev#create-a-skeleton-add-on).
### Quick Start
`go get` this middleware
```shell
$ go get github.com/abiosoft/hello-caddy
```
`cd` into the source directory
```shell
$ cd $GOPATH/src/github.com/abiosoft/hello-caddy
```
Run [caddydev](https://github.com/caddyserver/caddydev) to start Caddy with your new middleware.
```shell
$ caddydev
Starting caddy...
0.0.0.0:2015
```
Test the middleware
```
$ curl localhost:2015
Hello, I'm a caddy middleware
```
### This is magic, how did it happen ?
By default, Caddy looks for [`Caddyfile`](https://caddyserver.com/docs/caddyfile) in the current directory and this repository contains a suitable one. **Note** our new directive `hello`.
```conf
0.0.0.0
hello
```
This repository also contains a [`config.json`](https://github.com/caddyserver/caddydev#1-configjson-file) file.
```
{
"directive" : "hello"
}
```
#### Digging into the source, hello.go
Firstly, Caddy initializes the middleware using a compatible [Setup function](https://godoc.org/github.com/mholt/caddy/caddy#SetupFunc). **Note** that the function name must be `Setup`.
```go
func Setup(c *setup.Controller) (middleware.Middleware, error) {
return func(next middleware.Handler) middleware.Handler {
return &handler{}
}, nil
}
```
Then process requests using the middleware's [Handler](https://godoc.org/github.com/mholt/caddy/middleware#Handler). All that this middleware is doing is to write "Hello, I'm a caddy middleware".
```go
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
w.Write([]byte("Hello, I'm a caddy middleware"))
return 200, nil
}
```
It is not magic afterall ;).