Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "encoding/json"
  6. "io/ioutil"
  7. )
  8.  
  9. type User struct {
  10. Name string `json:"name"`
  11. }
  12.  
  13. // define function signatures as interface ...
  14. type Loader func(string) (interface{}, error)
  15. type Validator func(interface{}) bool
  16.  
  17. // Create a Loader instance with parameter in the constructor (ie, CreateLoader)
  18. func CreateLoader(baseDir string) Loader {
  19.  
  20. // inner function, ie private function
  21. unmarshalUser := func(data []byte) (*User, error) {
  22. u := &User{}
  23. if err := json.Unmarshal(data, u); err != nil {
  24. return nil, err
  25. }
  26.  
  27. return u, nil
  28. }
  29.  
  30. // return the loader, variables and methods in the current scope
  31. // are just private.
  32. return func(name string) (interface{}, error) {
  33. if data, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", baseDir, name)); err != nil {
  34. return nil, err
  35. } else {
  36. return unmarshalUser(data)
  37. }
  38. }
  39. }
  40.  
  41. // Create a Validator instance with parameter in the constructor (ie, CreateValidator)
  42. func CreateValidator() Validator {
  43.  
  44. validateUser := func(user *User) bool {
  45. return len(user.Name) > 0
  46. }
  47.  
  48. return func(v interface{}) bool {
  49. switch t := v.(type) {
  50. case *User:
  51. return validateUser(t)
  52.  
  53. default:
  54. return false
  55. }
  56. }
  57. }
  58.  
  59. // of course, we can pass dependencies ... no need to know the method name ...
  60. func execute(loader Loader, validator Validator) {
  61. // some codes
  62. if data, err := loader("data.json"); err != nil {
  63. fmt.Print("Error while loading: ", err)
  64. } else {
  65. if validator(data) {
  66. fmt.Printf("Data is valid")
  67. } else {
  68. fmt.Printf("Data is not valid")
  69. }
  70. }
  71. }
  72.  
  73. func main() {
  74.  
  75. // create closures with one responsibility ...
  76. loader := CreateLoader("./fixtures");
  77. validator := CreateValidator();
  78.  
  79. execute(loader, validator)
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement