首頁 >後端開發 >Golang >帶有數據之星的即時網絡

帶有數據之星的即時網絡

DDD
DDD原創
2024-10-13 06:12:02734瀏覽

realtime web with data-star

這是一個小例子,展示了使用 https://data-star.dev 在 golang 中如何簡單乾淨地實現「即時」事物

伺服器時鐘:

cmd/app/main.go

package main

import (
    "log"
    "net/http"

    "github.com/blinkinglight/clock-data-star/handlers"
    "github.com/go-chi/chi/v5"
)

func main() {
    router := chi.NewRouter()

    handlers.SetupHome(router)

    log.Printf("Starting server on :3000")
    log.Fatal(http.ListenAndServe(":3000", router))
}

handlers/handlers.go

package handlers

import (
    "net/http"
    "time"

    "github.com/blinkinglight/clock-data-star/web/views"
    "github.com/delaneyj/datastar"
    "github.com/go-chi/chi/v5"
)

func SetupHome(router chi.Router) {

    homeRoute := func(w http.ResponseWriter, r *http.Request) {
        views.ClockPage().Render(r.Context(), w)
    }

    clockRoute := func(w http.ResponseWriter, r *http.Request) {
        sse := datastar.NewSSE(w, r)
        ticker := time.NewTicker(time.Second)
        for {
            select {
            case <-r.Context().Done():
                ticker.Stop()
                return
            case <-ticker.C:
                datastar.RenderFragmentTempl(sse, views.ClockFragment(time.Now().Format("15:04:05")))
            }
        }
    }

    router.Get("/", homeRoute)
    router.Get("/clock", clockRoute)
}

web/views/page.templ

package views

templ Page() {
    <!DOCTYPE html>
    <html>
        <head>
            <script type="module" defer src="https://cdn.jsdelivr.net/npm/@sudodevnull/datastar"></script>
        </head>
        <body>
            <div>
                { children... }
            </div>
        </body>
    </html>
}

和 web/views/clock.templ

package views

import "github.com/delaneyj/datastar"

templ ClockPage() {
    @Page() {
        <div data-on-load={ datastar.GET("/clock") }>
            <h1>Clock</h1>
            <div id="clock"></div>
        </div>
    }
}

templ ClockFragment(t string) {
    <div id="clock">
        { t }
    </div>
}

就是這樣。

工作範例在這裡:https://github.com/blinkinglight/clock-data-star

以上是帶有數據之星的即時網絡的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn