Skip to content

Instantly share code, notes, and snippets.

@Micrified
Created June 6, 2024 23:19
Show Gist options
  • Save Micrified/cce87caf086a88295759763ef37dfd0c to your computer and use it in GitHub Desktop.
Save Micrified/cce87caf086a88295759763ef37dfd0c to your computer and use it in GitHub Desktop.
Wrapping interface methods
package main
import (
"fmt"
"encoding/json"
)
func ExpectJSON [T any] (b []byte) (T, error) {
var (
err error
data T
)
err = json.Unmarshal(b, &data)
return data, err
}
// --- Restful, HTTP Method
type Restful interface {
Post(any) error
}
type Method func (Restful, any) error
// --- Adapter, on Methods
type Adapter interface {
Auth(Method) Handler
}
type Handler func (Restful, []byte) error
// --- Controller
type ControllerType [T any] struct {
Name string
Methods map[string]Handler
Data T
}
func Auth (m Method) Handler {
return func(r Restful, b []byte) error {
// Unmarshal
d, err := ExpectJSON[Frame[any]](b)
// Auth
if err = Check(d); nil != err {
return err
}
// OK
return m(r, d.Data)
}
}
// --- Auth
type Frame[T any] struct {
Username string
Data T
}
func Check(m Frame[any]) error {
if m.Username == "bob" {
return nil
}
return fmt.Errorf("Unable")
}
// --- Implementation
type LoginData struct {}
type LoginController ControllerType[LoginData]
type Login struct {
Date string
}
func (c *LoginController) Post (t any) error {
// Unmarshal
//fmt.Println(t.(Login))
fmt.Printf("%+v\n", t)
return nil
}
// --- Main
func main() {
lc := &LoginController{
Name: "Login",
Methods: map[string]Handler {
"post" : Auth(Restful.Post),
},
}
msg := Frame[Login] {
Username: "bob",
Data: Login {
Date: "Fri Jun 7",
},
}
buffer, _ := json.Marshal(&msg)
m, _ := lc.Methods["post"]
m(lc, buffer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment