Files
go-common/examples/http_handler_example.go

53 lines
1.0 KiB
Go

//go:build example
// +build example
package main
import (
"log"
"net/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
if err := factory.Init("config.json"); err != nil {
log.Fatal(err)
}
app := factory.Default()
chain := app.MiddlewareChain()
http.Handle("/users", chain.ThenFunc(listUsers))
log.Fatal(http.ListenAndServe(":8080", nil))
}
func listUsers(w http.ResponseWriter, r *http.Request) {
app := factory.Default()
i18n, _ := app.I18n()
h := commonhttp.NewHandler(w, r, commonhttp.WithI18n(i18n))
var req struct {
Keyword string `json:"keyword"`
commonhttp.PaginationRequest
}
if err := h.ParseJSON(&req); err != nil {
h.Error("common.invalid_request")
return
}
p := h.Pagination()
users := []User{
{ID: 1, Name: "User1", Email: "user1@example.com"},
{ID: 2, Name: "User2", Email: "user2@example.com"},
}
h.SuccessPage(users, 100)
_ = p
}