Skip to content

Instantly share code, notes, and snippets.

@yursan9
Created December 14, 2021 12:28
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 yursan9/7f7fc9d17fb1fddf3e813bdd1071bb65 to your computer and use it in GitHub Desktop.
Save yursan9/7f7fc9d17fb1fddf3e813bdd1071bb65 to your computer and use it in GitHub Desktop.
Golang Handler using generics
package main
import (
"fmt"
"net/http"
)
type HandlerFunc[T, V any] func(data T, r *http.Request, rw http.ResponseWriter) (V, error)
type BindFunc[T any] func(r *http.Request) T
type Route[T, V any] struct {
Method string
Pattern string
HandlerFunc HandlerFunc[T, V]
BindFunc BindFunc[T]
}
type Person struct {
Name string
}
type PersonReq struct {
Name string
}
func PersonReqBind(r *http.Request) PersonReq {
return PersonReq{
Name: "Yuri",
}
}
func CreatePerson(data PersonReq, r *http.Request, rw http.ResponseWriter) (Person, error) {
return Person{
Name: data.Name,
}, nil
}
func Handle[T, V any](method, pattern string, handler HandlerFunc[T, V], bindFunc BindFunc[T]) *Route[T, V] {
r := &Route[T, V]{
Method: method,
Pattern: pattern,
HandlerFunc: handler,
BindFunc: bindFunc,
}
return r
}
func main() {
r := Handle(http.MethodGet, "/", CreatePerson, PersonReqBind)
var data PersonReq
if r.BindFunc != nil {
data = r.BindFunc(nil)
}
fmt.Println(r.HandlerFunc(data, nil, nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment