Skip to content

Instantly share code, notes, and snippets.

@Tmw
Created May 15, 2023 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tmw/d1cdc97d9a7a42a820473fde0ab05d96 to your computer and use it in GitHub Desktop.
Save Tmw/d1cdc97d9a7a42a820473fde0ab05d96 to your computer and use it in GitHub Desktop.
Quick experimentation on how to setup generic restful responses using Go
package main
import (
"encoding/json"
"fmt"
)
type Formatter interface {
Format() any
}
type BookModel struct {
AuthorName string
BookName string
ISBN string
PageCount int
}
func (b BookModel) Format() any {
type Formatted struct {
AuthorName string `json:"author_name"`
BookName string `json:"book_name"`
ISBN string `json:"isbn"`
PageCount int `json:"page_count"`
}
return Formatted {
AuthorName: b.AuthorName,
BookName: b.BookName,
ISBN: b.ISBN,
PageCount: b.PageCount,
}
}
type ResponseList struct {
Items []any `json:"items"`
Total int`json:"total"`
Page int`json:"page"`
PageSize int`json:"page_size"`
}
func (rl ResponseList) Format() any {
return rl
}
func main() {
b := getBooks(20)
out, err := respondList(b, 12, 1, 12)
if err != nil {
panic(err)
}
fmt.Printf("out: %+v\n", string(out))
}
func respond[T Formatter](v T) ([]byte, error) {
return json.MarshalIndent(v.Format(), "", " ")
}
func respondList[T Formatter](items []T, total, page, pageSize int) ([]byte, error) {
// format all items first
formatted := make([]any, len(items))
for idx := range items {
formatted[idx] = items[idx].Format()
}
// setup response model
response := ResponseList {
Items: formatted,
Page: page,
PageSize: pageSize,
Total: total,
}
return json.MarshalIndent(response, "", " ")
}
func getBooks(n int) []BookModel {
res := make([]BookModel, n)
for i := 0; i < n; i++ {
res[i] = getBook()
}
return res
}
func getBook() BookModel {
return BookModel{
AuthorName: "tables, bobby",
BookName: "How to drop 'em all",
ISBN: "123.13.43812.1993",
PageCount: 12,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment