Created Using Caddy Middleware in Your Own Programs (markdown)

Matt Holt 2015-04-25 17:56:42 -06:00
parent 56c629ef89
commit dd4dc54044

@ -0,0 +1,55 @@
This page describes how to import and use Caddy middleware in your own Go application. It's pretty easy, but if you've never used Go's net/http package before, you might want to take [a basic tutorial](https://golang.org/doc/articles/wiki/) first.
## Compatible Handlers
To use your handler with Caddy's middleware, your ServeHTTP method must return `(int, error)` as described [in the documentation](http://godoc.org/github.com/mholt/caddy/middleware#HandlerFunc). Basically, the `int` is an HTTP status code and the `error` is the error that occurred, if any. This implies different behavior for handling errors than you may be used to with http.Handler, but that's the only difference.
## Finding Middleware
Caddy's middleware are found in the [middleware](https://github.com/mholt/caddy/tree/master/middleware) folder of the repository. You may import any of those packages into your program.
## Getting It
Just like any Go package, you can use go get to download it. For example, if you want to add the extension middleware to your app:
```bash
$ go get github.com/mholt/caddy/middleware/extensions
```
Don't forget to add the import line to your program if your editor doesn't do it for you.
## Configuration & Chaining
Your web app will need to set up the middleware and insert it into your handler chain. To use the extension middleware, for example, you might do something as simple as:
```go
ext := extensions.Ext{
Next: myHandler.ServeHTTP,
Root: "../website",
Extensions: []string{".html", ".txt"},
}
```
## Using It With net/http
So you've chained up your middleware, but it doesn't satisfy net/http's interface! Now what? The Go Blog [has an elegant solution](http://blog.golang.org/error-handling-and-go). Your application can implement http.Handler and call the middleware chain:
```go
// Could also use your own existing type or alias
// middleware.HandlerFunc instead
type appHandler func(http.ResponseWriter, *http.Request) (int, error)
// Satisfy http.Handler and handle errors in a consistent way
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if status, err := fn(w, r); err != nil {
// Handle errors better than this
http.Error(w, err.Error(), status)
}
}
```
There are several good variations of this pattern, so you may do as you like.
## That's It
From here you should be able to wire up the rest of your app with `http.ListenAndServe()` without any trouble. If you encounter problems with the middleware or would like to discuss it, feel free to hack on it a bit, and contribute to make Caddy better.