John Siu Blog

Tech - Business Tool, Personal Toys

Hugo - My IP With Caddy

☰ Table of Content

There are websites that show your internet IP, ever want to create your own?

Hugo is a static site generator, there is no server side processing once deployed. However Caddy v2 templates feature is giving this a twist.

Following is a simple way to create a fully themed Hugo “show my ip” page with Caddy v2 servers.

Create Page

Create a new Hugo page:

1
hugo new home/myip.md

Inside myip.md with following content:

1
2
3
4
5
---
title: "MY IP"
---

{{.RemoteIP}}

{{.RemoteIP}} is a Caddy template function1.

Create a menu entry in config.toml

1
2
3
4
[menu]
[[menu.main]]
name = "My IP"
url = "/home/myip/"

Generate and deploy your site.

Caddyfile

In Caddyfile, add following line inside your site config:

1
templates /home/myip/

The templates line tell caddy server to treat /home/myip/ as a template2.

Take this site Caddyfile as example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
johnsiu.com {
	encode gzip
	root * /www/site/johnsiu.com
	file_server
	handle_errors {
		rewrite * /{http.error.status_code}.html
		file_server
	}
	templates /home/myip/
}

Restart caddy server.

Plain Text

You can also create a plain text version to be used by curl command as I shown in How to Find My Public IP.

With File

In Hugo site root, create static/myip/intex.html:

1
{{.RemoteIP}}

Again, add templates line in Caddyfile:

1
templates /myip/

Generate and deploy your site, restart caddy server.

Test from command line:

1
2
curl -4 https://johnsiu.com/myip/
curl -6 https://johnsiu.com/myip/

Caddyfile Only

This post on Caddy forum shown it can be done with just Caddyfile.

1
2
3
4
5
myip.example.com {
  header Content-Type text/plain
  respond "{{.RemoteIP}}"
  templates
}

The template text is embedded directly in respond, no extra file required.

I turned it into a snippet here.

Simultaneous IPv4 IPv6

Hugo - My IP Page With Javascript will explore how to show IPv4 and IPv6 at the same time.

John Siu

Update: 2022-05-10
comments powered by Disqus