Created
December 14, 2021 12:28
-
-
Save yursan9/7f7fc9d17fb1fddf3e813bdd1071bb65 to your computer and use it in GitHub Desktop.
Golang Handler using generics
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" | |
"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