DEV Community

Hanzla Baig
Hanzla Baig

Posted on • Originally published at dev.to on

2 2 2 2 2

Hybrid Rendering Architecture using Astro and Go Fiber

In this architecture, Astro is responsible for static site generation and asset optimization , creating pre-rendered HTML, CSS, and JavaScript files for high performance and efficient delivery. Go Fiber handles dynamic data processing, API integration, and serving the static files , providing real-time data updates and efficient server-side routing and middleware management. This combination leverages the strengths of both technologies to create a performant and scalable web application.

Full Example of Hybrid Rendering Architecture using Astro and Go Fiber

Here's a step-by-step guide to creating a web application using the Hybrid Rendering Architecture with Astro and Go Fiber.

1. Set Up the Astro Project

  1. Install Astro and create a new project:
   npm create astro@latest
   cd my-astro-site

Enter fullscreen mode Exit fullscreen mode
  1. Create a page in Astro:

Create src/pages/index.astro:

   ---
   export const prerender = true;
   ---

   <!DOCTYPE html>
   <html lang="en">
   <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>{Astro.props.title}</title>
     <link rel="stylesheet" href="/assets/style.css">
   </head>
   <body>
     <h1>{Astro.props.title}</h1>
     <p>{Astro.props.message}</p>
     <script src="/assets/script.js"></script>
   </body>
   </html>

Enter fullscreen mode Exit fullscreen mode
  1. Add CSS and JS files:

Create src/assets/style.css:

   body {
     font-family: Arial, sans-serif;
     background-color: #f0f0f0;
     margin: 0;
     padding: 20px;
   }

Enter fullscreen mode Exit fullscreen mode

Create src/assets/script.js:

   document.addEventListener('DOMContentLoaded', () => {
     console.log('Astro and Go Fiber working together!');
   });

Enter fullscreen mode Exit fullscreen mode
  1. Build the Astro project:
   npm run build

Enter fullscreen mode Exit fullscreen mode

2. Set Up the Go Fiber Project

  1. Create a new Go project and install dependencies:
   go mod init mysite
   go get github.com/gofiber/fiber/v2

Enter fullscreen mode Exit fullscreen mode
  1. Create the main Go file:

Create main.go:

   package main

   import (
       "log"
       "github.com/gofiber/fiber/v2"
       "path/filepath"
       "encoding/json"
       "io/ioutil"
       "bytes"
       "os/exec"
       "net/http"
   )

   // Function to render Astro template
   func renderAstroTemplate(templatePath string, data map[string]interface{}) (string, error) {
       cmd := exec.Command("astro", "build", "--input", templatePath)

       // Pass data to template via stdin
       jsonData, err := json.Marshal(data)
       if err != nil {
           return "", err
       }
       cmd.Stdin = bytes.NewBuffer(jsonData)

       output, err := cmd.CombinedOutput()
       if err != nil {
           return "", fmt.Errorf("failed to execute astro build: %s", string(output))
       }

       // Read generated file
       outputPath := filepath.Join("dist", "index.html")
       content, err := ioutil.ReadFile(outputPath)
       if err != nil {
           return "", err
       }

       return string(content), nil
   }

   func main() {
       app := fiber.New()

       // Serve static files from the dist directory
       app.Static("/", "./my-astro-site/dist")

       app.Get("/", func(c *fiber.Ctx) error {
           data := map[string]interface{}{
               "title": "My Astro Site",
               "message": "Welcome to my site built with Astro and Go Fiber!",
           }

           htmlContent, err := renderAstroTemplate("./my-astro-site/src/pages/index.astro", data)
           if err != nil {
               return c.Status(http.StatusInternalServerError).SendString(err.Error())
           }

           return c.Type("html").SendString(htmlContent)
       })

       log.Fatal(app.Listen(":3000"))
   }

Enter fullscreen mode Exit fullscreen mode

3. Run the Application

  1. Start the Go Fiber server:
   go run main.go

Enter fullscreen mode Exit fullscreen mode
  1. Access the website:

Open your browser and navigate to http://localhost:3000.

Summary

In this example, Astro handles the static site generation, creating optimized HTML, CSS, and JavaScript files. Go Fiber serves these static files and dynamically injects data into the templates, allowing for real-time data updates. This hybrid rendering architecture leverages the strengths of both technologies to create a performant and scalable web application.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay