Caddy a Web Server_ server with Go implementation other

Source: Internet
Author: User
Tags documentation fpm function prototype mkdir php server

This is a Web server era, apache2 and Nginx dances, in pursuit of the ultimate performance of the road, not the highest, only higher. But this is another era of personalized pursuit, some Web server does not squeeze the "performance ascension" of this bridge, but has its own positioning, caddy is such an open source Web server.

Caddy's author Matt Holt The Caddy goal in Caddy's official website and FAQ as follows: Other Web servers are designed for the web, caddy for human design. Functionally positioned, unlike nginx, which often act as the front-end reverse proxy, Caddy is committed to becoming an easy-to-use static file Web Server. Can see Caddy main usability, use configuration simple. And thanks to Go's cross-platform features, Caddy easily supports the three main platforms: Windows, Linux, and Mac. In the Caddy developer documentation, we can see that caddy can also run on Android (Linux arm). Caddy current version is 0.7.1, is not stable, and subsequent versions may vary greatly, even with the previous version is not compatible, so the author does not recommend caddy in the production environment to be heavily used.

Focus on Caddy Because caddy fills in the blank space of the go on the general Web server (there may be other, but I don't know), while the Web server in goes "responds" to the recent trend of Golang to C-C is gone! Even the Caddy author mentions that Caddy's goals are not as nginx. But in the future who knows? Once the go performance is high enough, once the caddy is stable enough, someone will naturally use it in the production environment of some applications instead of Nginx or apache2. A set of all go system, in the deployment, Operation dimension is also advantageous.

I. Installation and operation of Caddy

As with many go apps, we can find the latest release (currently 0.7.1) binaries directly from Caddy's github.com releases page. The Caddy_darwin_amd64.zip is used here.

After the decompression, enter the directory, direct execution./caddy can run the caddy.

$caddy
0.0.0.0:2015

Access to localhost:2015 in the browser, there is no expected to appear on the page like "Caddy works!" Instead of the default welcome page such as "404 Not Found". Although this indicates that Caddy has been work, no default Welcome page is, after all, unfriendly to caddy Beginer. A sugguestion issue has been mentioned here to the author.

Second, Caddy principle

The Go Net/http Standard library has provided an implementation of HTTP server, most of which can meet your needs, whether it be functional or performance. Caddy is essentially a go web app, and it's also import net/http, embedded *http. Server, and provides services for each request through the handler Servehttp method. Caddy uses HTTP. Fileserver as the basis for working with static files. The allure of Caddy is its middleware, which middleware a string of middleware chain to provide a flexible Web service. In addition, the middleware in Caddy can also be used independently of caddy.

Caddy reads the configuration from the Caddyfile (default) file in the current directory, but you can also specify the profile path by-conf. Caddyfile's configuration format is really easy, which is also consistent with Caddy's goals.

Caddyfile always starts with the addr of the site.

The Caddyfile sample for a single site is as follows:

Caddyfile
localhost:2015
gzip
log./2015.log

Caddy also supports the configuration of multiple sites, similar to the VirtualHost configuration (80-port multiplexing):

Caddyfile
foo.com:80 {
log./foo.log
gzip
}

bar.com:80 {
log./bar.log
gzip
}

To achieve a consistent style, a single site is best configured with the following format (called Server block within the code):

localhost:2015 {
gzip
log./2015.log
}

This Caddyfile profile template style is similar to the following:

Host1:port {
middleware1
middleware2 {
...
}
...
}

Host2:port {
middleware1
middleware2 {
...
}
...
}
... ...

For middleware, there are more detailed descriptions and examples in the Caddy documentation. For caddy Such a young open source project, its documentation is relatively complete, although it can not be compared with Nginx, Apache.

Caddy in the middleware is a realization of the middleware. The struct of the handler interface, such as gzip this middleware:

Middleware.go
Type middleware func (Handler) Handler
type Handler interface {
servehttp (http. Responsewriter, *http. Request) (int, error)
}

//gzip/gzip.go
type gzip struct {
Next middleware. Handler
}

func (g Gzip) servehttp (w http. Responsewriter, R *http. Request) (int, error) {
if!strings. Contains (R.header.get ("accept-encoding"), "gzip") {return
g.next.servehttp (W, R)
}
...
.. GZ: = Gzipresponsewriter{writer:gzipwriter, responsewriter:w}

//Any response in forward middleware'll now is COM Pressed
status, err: = G.next.servehttp (GZ, R)
...
}

Middleware. The function prototype of handler is different from Http.handler, and can not be used directly as Http.server handler. Caddy used the following idiomatic go pattern:

Type Apphandler func (http. Responsewriter, *http. Request) (int, error)

Func (FN Apphandler) servehttp (w http. Responsewriter, R *http. Request) {
If status, err: = FN (W, R); Err!= nil {
http. Error (W, err.) Error (), status)
}
}

Of course there are many variants of this pattern, but the idea is broadly similar. A middleware chain is roughly the Handler1 (Handler2 (HANDLER3)) call pass.

As I said before, Caddy is based on HTTP. Fileserver's static file Web Server,fileserver is always the last link to middleware chain, and if you don't have any middleware configured, your server is a static file server.

Iii. Typical application of caddy

"Static file Server"

The most basic application of caddy is actually a static file server, with HTTP at the bottom. Fileserver Hosting, of course, Caddy encapsulates http. Fileserver, do some blocking processing, and finally pass W, R to HTTP. Servecontent to process file data.

The first time you execute./caddy, a static file server is actually started. However, this server does not support your navigate directory by default. If you know the website root directory (if you do not specify root, then caddy executes the current path as the website root path) under the file name, such as Foo.txt, you can enter in the browser: localhost:2015/ Foo.txt,caddy will perform the correct service and the browser will also display the full text of foo.txt.

For static file Server,caddy supports the website root path to first find out if there are four files below:

Caddy/middleware/browse/browse.go
var indexpages = []string{
"index.html", "
index.htm",
" Default.html ",
" default.htm ",
}

If you find one, then first return the contents of this file, this is the static site's home page.

If you want to support directory file list browsing, you need to configure the Browse middleware for website, so that for directories without index file, we can see a list of catalog files.

localhost:2015 {
Browse

"Reverse proxy"

The Caddy supports basic reverse proxy functionality. The reverse proxy configuration is implemented through proxy middleware.

localhost:2015 {
log./2015.log

proxy/foo localhost:9001
proxy/bar localhost:9002
}

When you visit Localhost:2015/foo, you are actually accessing the 9001-Port service program;
When you access Localhost:2015/bar, you are actually accessing the 9002-Port service program.

"Load Balancing"

Caddy supports load balancing configurations and supports three load balancing algorithms: Random (Random), least_conn (minimum connection), and Round_robin (polling scheduling).

Load balancing is also implemented through proxy middleware.

localhost:2015 {
log./2015.log

proxy/localhost:9001 localhost:9003 {
policy round_robin
}
Proxy/bar localhost:9002 localhost:9004 {
policy least_conn
}
}

"Support FASTCGI Agent"

Caddy also supports FASTCGI proxies, which can send requests through the FASTCGI interface to the backend implementation fastcgi server. Let's take the example of a "Hello World" PHP server.

The Mac OS has its own php-fpm, a PHP CGI process manager that implements the fastcgi. Caddy sends the request to the PHP-FPM listening port, which initiates the PHP-CGI interpreter, interprets the index.php, and returns the result to caddy.

The PHP-FPM on Mac OS does not start randomly by default. We need to simply configure:

$mkdir Phptest
$mkdir-P PHPTEST/ETC
$mkdir-P Phptest/log
$CD Phptest
$sudo Cp/private/etc/php-fpm.conf.default./etc
$CD./etc
$sudo chown Tony Php-fpm.conf.default
$MV Php-fpm.conf.default php-fpm.conf

Edit php-fpm.conf to ensure that the following two items are in a non annotation state:

Error_log = Log/php-fpm.log
Listen = 127.0.0.1:9000

We communicate via network socket for fastcgi.

Go back to the Phptest directory and execute:

Php-fpm-p ~/test/go/caddy/phptest

After the execution, the PHP-FPM will be transferred to the background execution.

Next we'll configure Caddyfile:

localhost:2015 {
fastcgi/127.0.0.1:9000 php
log./2015.log
}

The implication here is that all requests are forwarded to Port 9000, where PHP is a preset (preconfigured collection) equivalent to:

Ext. php
split. PHP
Index index.php

We create a index.php file in the Phptest directory, which reads as follows:

<?php echo "Hello world\n";?>

OK, now start caddy, and use the browser to access localhost:2015 try. You will see "Hello World" presented in the browser.

"Git Push release"

For some static sites, Caddy supports GIT directive, which enables you to pull the latest updates to the server at server startup and at run time git pull your project library.

Two examples are given in the Caddy documentation:

The first is a PHP site that periodically pull the project library to implement the server update:

Git git@github.com:user/myphpsite {
key/home/user/.ssh/id_rsa
}
fastcgi/127.0.0.1:9000 php

The second is a static site, supported by Hugo, that executes the Hugo command to generate a new static page after each pull:

git github.com/user/site {
path.. /
then Hugo–destination=/home/user/hugosite/public
}

Note: git directive is not middleware, but a separate goroutine implementation.

Iv. Summary

The Caddy function is not limited to a few examples above, it is just a few of the most common scenes. Caddy is still very young, the application is not much, but the well-known Golang website gopheracademy.com (Gophercon organization) is by Caddy support. Caddy is also actively evolving, with an interest in gopher sustainable attention.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.