Hybrid Rendering Architecture using Astro and Go Fiber

YURII DE. - Jul 6 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .