Sobes.tech
Senior

package main import ( "io" "net/http" "strconv" "time" ) // getData returns almost static data, yet, sometimes it changes. func getData() int { time.Sleep(time.Millisecond * 100) return 1 } func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { _, _ = io.WriteString(writer, strconv.Itoa(getData())) }) if err := http.ListenAndServe(":8080", mux); err != nil { panic(err) } }

sobes.tech AI

Answer from AI

In this Go HTTP server code, the getData() function simulates fetching almost static data with a slight delay.

To improve performance and reduce delays in request processing, you can implement caching of the getData() result, updating it asynchronously at a certain interval.

An improved example using goroutines and an atomic cache:

package main

import (
	"io"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

var cachedData atomic.Value

func refreshData() {
	for {
		data := getData()
		cachedData.Store(data)
		time.Sleep(time.Second) // update every second
	}
}

func getData() int {
	time.Sleep(time.Millisecond * 100) // simulate delay
	return 1
}

func main() {
	cachedData.Store(0) // initialization
	go refreshData()

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		data := cachedData.Load().(int)
		_, _ = io.WriteString(w, strconv.Itoa(data))
	})

	if err := http.ListenAndServe(":8080", mux); err != nil {
		panic(err)
	}
}

This approach allows:

  • Avoid blocking and delays in processing each request.
  • Update data in the background at the desired frequency.
  • Quickly serve cached data to clients.

If the data changes infrequently, you can increase the update interval to reduce load.

package main import ( "io" "net/http" "strconv"… - sobes.tech