6 Essential Go Tricks to Boost Your Backend Development

This article presents six practical Go techniques—including loop labels for prime number generation, IP address conversion, octal UTF‑8 decoding, a lightweight HTTP utility library, a concise debug logging helper, and a Go‑based httpbin replacement—complete with code examples, usage notes, and visual results.

Cloud Native Technology Community
Cloud Native Technology Community
Cloud Native Technology Community
6 Essential Go Tricks to Boost Your Backend Development

01. Loop Labels for Prime Numbers

Go's for loops can use labeled continue to break out of nested loops without auxiliary flags. Example prints primes below 10.

package main

import "fmt"

func main() { printPrime(10) }

func printPrime(maxNum int) {
next:
    for outer := 2; outer < maxNum; outer++ {
        for inner := 2; inner < outer; inner++ {
            if outer%inner == 0 {
                continue next
            }
        }
        fmt.Printf("%d
", outer)
    }
    fmt.Println("Completed")
}

Equivalent C implementation requires a flag variable.

#include <stdio.h>

void printPrime(int maxNum) {
    int outer, inner;
    int flag;
    for (outer = 2; outer < maxNum; outer++) {
        flag = 1;
        for (inner = 2; inner < outer; inner++) {
            if (outer % inner == 0) {
                flag = 0;
                break;
            }
        }
        if (flag == 1) {
            printf("%d
", outer);
        }
    }
    printf("Completed
");
}

int main() { printPrime(10); return 0; }

02. IP Address String ↔ Integer Conversion

Utility functions to convert IPv4 string to a 64‑bit integer and back, using net.ParseIP and math/big.

package main

import (
    "fmt"
    "math/big"
    "net"
)

func InetNtoA(ip int64) string {
    return fmt.Sprintf("%d.%d.%d.%d",
        byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}

func InetAtoN(ip string) int64 {
    ret := big.NewInt(0)
    ret.SetBytes(net.ParseIP(ip).To4())
    return ret.Int64()
}

func main() {
    ip := "192.168.78.123"
    ipInt := InetAtoN(ip)
    fmt.Printf("convert string ip [%s] to int: %d
", ip, ipInt)
    fmt.Printf("convert int ip [%d] to string: %s
", ipInt, InetNtoA(ipInt))
}

Check that net.ParseIP(ip).To4() is not nil before using.

03. Octal UTF‑8 to Chinese

Convert octal‑escaped UTF‑8 sequences (e.g., \346\200\241) back to readable characters using a regular‑expression based function.

package main

import (
    "fmt"
    "regexp"
    "strconv"
)

func convertOctonaryUtf8(in string) string {
    s := []byte(in)
    reg := regexp.MustCompile(`\\[0-7]{3}`)
    out := reg.ReplaceAllFunc(s, func(b []byte) []byte {
        i, _ := strconv.ParseInt(string(b[1:]), 8, 0)
        return []byte{byte(i)}
    })
    return string(out)
}

func main() {
    s1 := "\346\200\241" // literal
    s2 := `\346\200\241` // raw string
    fmt.Println("s1 =", s1)
    fmt.Println("s2 =", s2)
    s3 := convertOctonaryUtf8(s2)
    fmt.Println("s3 =", s3)
}

04. Simplified HTTP Requests with httputil

A lightweight library abstracts common HTTP client steps (URL construction, body handling, timeout, error checking, response parsing). It supports GET, POST, PUT, PATCH, DELETE and payload types string, []byte, map, struct. Default timeout 30 s and JSON content type.

package main

import (
    "context"
    "log"

    hu "github.com/chinaran/httputil"
)

func main() {
    // GET example
    urlGet := "https://httpbin.org/get?hello=world"
    var respGetM map[string]interface{}
    if err := hu.Get(context.TODO(), urlGet, &respGetM, hu.WithLogTimeCost()); err != nil {
        log.Printf("Get %s err: %s", urlGet, err)
        return
    }
    log.Printf("Get %s map response: %+v", urlGet, respGetM)

    // POST example
    urlPost := "https://httpbin.org/post"
    req := map[string]string{"hello": "world"}
    var respPost struct{ Data string `json:"data"` }
    if err := hu.Post(context.TODO(), urlPost, &req, &respPost, hu.WithLogTimeCost()); err != nil {
        log.Printf("Post %s err: %s", urlPost, err)
        return
    }
    log.Printf("Post %s struct response: %+v", urlPost, respPost)
}

05. Quick Variable Inspection with debuglog

Utility functions for logging values without explicit formatting: Val, SpewVal (deep inspection via spew), ToJson, and ToJsonPretty.

package main

import "github.com/chinaran/debuglog"

type TestJson struct {
    Id   int64
    Name string
}

func main() {
    intVal := 123
    debuglog.Val(intVal)
    debuglog.Val(intVal, "prefix1")
    debuglog.Val(intVal, "prefix1", "prefix2")

    testJson := TestJson{Id: 987, Name: "alan"}
    debuglog.SpewVal(testJson, "testJson Spew")
    debuglog.ToJson(testJson, "testJson")
    debuglog.ToJsonPretty(testJson, "testJson Pretty")
}

06. go-httpbin – A Go‑Based HTTP Testing Service

A minimal reimplementation of httpbin using only the Go standard library. It adds response‑delay arguments, pretty‑printed JSON, environment query parameters, and an “anything” endpoint. Run with Docker:

docker run -p 8080:80 ghcr.io/chinaran/go-httpbin:1.2-alpine3.13

Example request:

curl http://go-httpbin/get
{
    "envs": {"HOSTNAME": "go-httpbin-6f55bbcfcd-skrxl"},
    "args": {},
    "headers": {...},
    "origin": "127.0.0.1:46756",
    "url": "http://go-httpbin/get"
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendDebuggingGolangGoHTTPutilitiesIP Conversion
Cloud Native Technology Community
Written by

Cloud Native Technology Community

The Cloud Native Technology Community, part of the CNBPA Cloud Native Technology Practice Alliance, focuses on evangelizing cutting‑edge cloud‑native technologies and practical implementations. It shares in‑depth content, case studies, and event/meetup information on containers, Kubernetes, DevOps, Service Mesh, and other cloud‑native tech, along with updates from the CNBPA alliance.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.