Hugo Doesn't Allow Writing to Files, Correct?

Hugo does not allow you to write to local files, even if just appending – corect?

Backgrounds:
I want to show a shortened URL to each of the pages on my website, on that page. SNSes often have a character-length limit so you very often need to use shortened URLs if you want to post about the pages.

Some shortened URL creator services allow API access (e.g., Spoo.me), which takes away the annoying hassle of creating shortened URLs one by one by hand. So I wanted to do handle the shortened URL inclusion this way:

  1. At the time of site generation, check if the page already has a shortened URL created for it. If so, great, just show it on page.
  2. If not, create a new shortened URL programmatically, and then show it.

To do this, you have to have a local “database”, which could be as simple as a text file made up of lines, each consisting of a pair of a long URL and its corresponding short URL. You need to be able to not just read it but also to append to it.

I thought the ideal time to do it is when Hugo generates a site. However, since Hugo does not allow you to write to files (you can read them), this cannot be done as part of Hugo’s site generation process. So I am guessing that I have to do it outside Hugo.

As long as your site is made up entirely of static content (i.e., no remote/external content), a relatively simple shell script should basically do, though it’s a pity that you’d have to duplicate some logic done by Hugo, such as deducing the final URL for each page.

However, there are pages Hugo creates for you for, e.g., authors, tags, categories, series, etc. If you create index.md files for them anyway, then you’re good. If not, you will have to special-case it.

I just wanted to make sure my understanding is correct. I am still very new to Hugo.

As a side note, providing simple writable persistent KV store functionality or something similar might be convenient for such use cases. I don’t think it sacrifices security much.

Thanks!

This might be helpful:
https://discourse.gohugo.io/t/short-urls/368/4

Thanks, @jmooring. That’s an interesting idea. The problem for me is that my domain name is long so this approach by itself will not really work for me, unfortunately. I need to use an external URL shortening service.

However, from your post, I’ve realized that I could take advantage of the fact you can have Hugo create and publish a file. That could work as a rudimentary filesystem-based database system that persists.

You can create files, but I don’t think you can append to an existing file.

But I think Hugo does support your use case. I would try to store the data in a `Page.Store` and use resources.FromString (with jsonify) to create a data file with the necessary mappings at the end (using a custom output format with a higher weight).