This article is published under a SIGNATURE 4.0 International (CC BY 4.0) license. Signature 4.0 International (CC BY 4.0)

Author: Su Yang

Creation time: 14 sep 2018 statistical word count: 2654 words reading time: 6 minutes to read this article links: soulteary.com/2018/09/14/…


Use Hugo to generate the API

With the booming development of SSG static generation tools, more and more static sites can be seen on the market. The general use method is to generate static pages through static spread point generation tools, and then publish.

I personally have been using Hugo for over a year and it is the number one in the open source community both in terms of stability and ease of use.

But is this kind of static site generator just for static sites? Of course not.

Hugo’s custom output feature, coupled with template generation, makes it easy to output some static APIS, while content can be written using Markdown and managed using a directory tree.

Whether used with statically generated sites, or simply provided to other external SPA applications are very convenient.

Here’s how to use the Hugo output API.

The statement configuration

You first need to specify json as the output type for the various pages in config.toml.

[outputs]
    page = ["json"]
    home = ["json"]
    teams = ["json"]
    section = ["json"]
    taxonomy = ["json"]
Copy the code

Define the template

Then,

Json, item.json, and list.json in layouts/_default/ using variables and template functions, for example:

{
    "title": "{{ .Title }}"."date": "{{ .Date }}"."type": "{{ .Type }}"."permalink" : "{{ .Permalink }}"."summary" : "{{ .Summary }}"
}
Copy the code

A Markdown file can be converted to the following:

{
  "data": {
    "title": "About"."date": "The 2018-02-09 11:47:06-0500-0500"."type": "page"."permalink": "/page/about/index.json"."summary": "An API about our school athletes!"}}Copy the code

List files, as well as standalone page files, refer to the sample project code I provided.

Adjust the output

Hugo’s output API relies on templates and uses a patchwork approach, so it is inevitable that the output will look like the following, with lots of useless whitespaces and possibly even error results.

{
	"data" : 
	{
    "name": "Frank J. Robinson"."contact" : "+ 1 (555) 555 5555"."permalink" : "/players/frank-j-robinson/index.json"."year" : "junior"
    
    	
    		,"practices" : "Monday, Thursday"
    	
    
    	
    		,"sports" : "soccer, baseball"}}Copy the code

In order to make the final product usable (performance, pre-delivered correctly), we need to use scripts to do extra processing on the product. Here I use Node.js:

'use strict';

const {readdirSync, statSync, readFileSync, writeFileSync} = require('fs');
const {join} = require('path');

function getAllFiles(dirPath, ext) {
  function flatten(arr) {
    return arr.reduce((flat, toFlatten) => flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten), []);
  }

  function scanDir(dirPath, ext) {
    const result = readdirSync(dirPath);
    if(! result.length)return [];
    return result.map((dirName) => {
      const filePath = join(dirPath, dirName);
      if (statSync(filePath).isDirectory()) {
        return scanDir(join(dirPath, dirName), ext);
      } else {
        if(! ext)return filePath;
        if (filePath.lastIndexOf(ext) === filePath.indexOf(ext) && filePath.indexOf(ext) > -1) return filePath;
        return ' '; }}); }return flatten(scanDir(dirPath, ext)).filter((file) => file);
}

const allMarkdownFiles = getAllFiles('./public'.'.json');
allMarkdownFiles.forEach((item) => {
  try {
    const jsonData = JSON.stringify(JSON.parse(readFileSync(item, 'utf8')));
    writeFileSync(item, jsonData);
  } catch (e) {
    console.error(`${item} content error.`);
    writeFileSync(item, JSON.stringify({code: 500, desc: 'Unexpected token'})); }});Copy the code

Save the script as checker.js and execute node Checker to perform batch correctness verification and result compression for Hugo’s products.

For example, after executing the processing script, the output above becomes:

{"data": {"name":"Frank J. Robinson"."contact":"+ 1 (555) 555 5555"."permalink":"/players/frank-j-robinson/index.json"."year":"junior"."practices":"Monday, Thursday"."sports":"soccer, baseball"}}
Copy the code

By configuring this script into CI, you can modify the Markdown file and automatically generate a high-performance, usable static API.

other

For example code, you can visit:

  • Hugo API Maker

Hugo has a bunch of other ways to play, but I’ll talk to you later.

-EOF


I now have a small toss group, which gathered some like to toss small partners.

In the case of no advertisement, we will talk about software, HomeLab and some programming problems together, and also share some technical salon information in the group from time to time.

Like to toss small partners welcome to scan code to add friends. (Please indicate source and purpose, otherwise it will not be approved.

All this stuff about getting into groups