Created
June 6, 2024 23:19
-
-
Save Micrified/cce87caf086a88295759763ef37dfd0c to your computer and use it in GitHub Desktop.
Wrapping interface methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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