Example Golang coloring of source code

Example Golang coloring of source code


package help

import (
	"fmt"
	"context"
	"os"
)

const hello = `hello`
var x = 'a'

// Hello prints "hello world"
func Hello(w io.Writer) {
     var txt = hello + " world"
     fmt.Println(txt)
}

/*
What func is this? '
*/
func do(ctx context.Context) error {
	for range 5 {
		select {
		case <- ctx.Done():
			break
		default:
			continue
			fmt.Print("oups")
			os.Exit(1)
		}
	}
	return nil
}


This example shows how to color Go code using Javascript and CSS.

It's a simple regexp based solution. It is not perfect but does the job good enough that it's easy to adapt should there be any special cases.


function gocolor(block) {
    const astring = '$1';
    const comment = '$1';
    const keyword = '$1';
    
    block.innerHTML = block.innerHTML
        .replace(/(".*"|`.*`|'.*')/g, astring)
        .replace(/(\/\/.*\n)/g, comment)
        .replace(/(\/\*[\s\S]*?\*\/)/g, comment)
        .replace(/^(package|import)/gm, keyword)
        .replace(/\b(var|const|map|interface|type|defer)\b/g, keyword)
        .replace(/\b(func|if|else|for|fallthrough)\b/g, keyword)
        .replace(/\b(switch|case|select|default)\b/g, keyword)
        .replace(/\b(break|continue|range|goto|return)\b/g, keyword);
}
document.querySelectorAll("code.go").forEach(gocolor);

Then use whatever colors you like.


<style>
.astring { color: #d14; }
.keyword { font-weight: bold; }
.comment, .comment * { color: darkgray; }
.comment * { font-weight: normal; }
</style>