gotlin/examples/http_server.gt

76 lines
2 KiB
Text

package examples.http
import context
import fmt
import github.com.uptrace.bun
import github.com.uptrace.bun.dialect.pgdialect
import github.com.uptrace.bun.driver.pgdriver
import database.sql
import net.http
import os
class BunUser(val Name: String)
class EpicControllerImpl(val db: *bun.DB) {
fun hello(w: http.ResponseWriter, r: *http.Request) {
fmt.Fprintln(w, "hello from gotlin")
}
fun bunHealth(w: http.ResponseWriter, r: *http.Request) {
val ctx = context.Background()
db.NewSelect().ColumnExpr("1").Scan(ctx)
fmt.Fprintln(w, "bun ok")
}
fun bunUsers(w: http.ResponseWriter, r: *http.Request) {
val ctx = context.Background()
val model = BunUser("gotlin")
db.NewCreateTable().Model(model).IfNotExists().Exec(ctx)
val user = BunUser("user-from-gotlin")
db.NewInsert().Model(user).Exec(ctx)
val total = db.NewSelect().Model(model).Count(ctx)
fmt.Fprintln(w, "bun users total:", total)
}
}
worker Counter {
var counter = 0
fun getCount(): Int {
return counter
}
fun increment() {
counter += 1
println(counter)
}
}
fun main() {
val postgresDsn = "postgresql://postgres:postgres@localhost/postgres?sslmode=disable"
val sqlDb = sql.OpenDB(
pgdriver.NewConnector(
pgdriver.WithDSN(postgresDsn)
)
)
val db = bun.NewDB(sqlDb, pgdialect.New())
val counter = Counter()
go {
while(true) {
select {
every(1000) -> counter.increment()
}
}
}
val epicController = EpicControllerImpl(db)
fmt.Println("serving http://localhost:8080")
http.HandleFunc("/", epicController.hello)
http.HandleFunc("/bun", epicController.bunHealth)
http.HandleFunc("/bun/users", epicController.bunUsers)
http.HandleFunc("/counter") { w, r ->
fmt.Fprintln(w, "bun users total:", counter.getCount())
}
http.ListenAndServe(":8080", http.DefaultServeMux)
}