Logo

dev-resources.site

for different kinds of informations.

Hybrid Rendering Architecture using Astro and Go Fiber

Published at
1/4/2025
Categories
go
astro
webdev
website
Author
hanzla-baig
Categories
4 categories in total
go
open
astro
open
webdev
open
website
open
Author
11 person written this
hanzla-baig
open
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.

astro Article's
30 articles in total
Favicon
Transforming Starlight into PDF: experience and insights
Favicon
Dynamic Routes in Astro (+load parameters from JSON)
Favicon
Import JSON Data in Astro (with Typescript)
Favicon
Use LateX in Astro.js for Markdown Rendering
Favicon
From Legacy to Lightning: Modernizing an Astro App with Daytona
Favicon
Having a Good Ol' RSS Feed in Astro
Favicon
A Date with Daytona: Exploring AstroJS and Sanity CMS
Favicon
Roast my portfolio
Favicon
SvelteKit VS Astro. laidback side by side
Favicon
โœ๏ธ Cross-Posting Astro Blog Posts to BlueSky Using GPT-4 ๐Ÿง 
Favicon
The best CMS for Astro: How to choose CMS for Astro projects
Favicon
Integrando Mรบltiples APIs de Blog en un Sitio Astro: Dev.to y Hashnode
Favicon
Construyendo un Portfolio Moderno con Astro y Tailwind CSS
Favicon
Hybrid Rendering Architecture using Astro and Go Fiber
Favicon
The Single Quote Curse: When AI Mistook an MDX Front Matter Issue for a YAML Bug
Favicon
First impressions of Astro: what I liked and disliked
Favicon
Mysterious Display in Astro: Unraveling the Secrets of the Development Environment
Favicon
Astro v5 Blog starter
Favicon
Letting the product shape the infrastructure
Favicon
Using Angular Inside of Astro
Favicon
AstroJS 5.1: Integra contenido de Dev.to de manera sencilla
Favicon
Less is More: The Case Against Feature-Bloated CMS
Favicon
Add content to your site: Markdown ๐Ÿ“
Favicon
Learn how to create an interactive pricing table with Astro JS, Tailwind CSS and Alpine.js
Favicon
So I created Linktree alternative...
Favicon
Debugging failed builds with Netlify
Favicon
API Keys y Variables de Entorno en Astro: Guรญa Completa de Seguridad
Favicon
Fighting with Redirects: A Journey of Astro Site Migration
Favicon
Why I Used Astro, Tailwind, and Qwik to Build My Personal Website
Favicon
Creating a Custom Astro Integration: Auto-Publishing to Hashnode

Featured ones: