Created
July 17, 2018 12:34
-
-
Save dimiro1/07f4d8ae51747887c194cd940c2301aa to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"time" | |
) | |
type Params interface { | |
String(r *http.Request, name string) string | |
} | |
type Binder interface { | |
Bind(r *http.Request, i interface{}) error | |
} | |
type ParamsBinder struct{} | |
func (p ParamsBinder) Bind(r *http.Request, i interface{}) error { | |
// cheating | |
myParams := i.(*MyParams) | |
dateStr := fmt.Sprintf( | |
"%s-%s-%s", | |
r.URL.Query().Get("year"), | |
r.URL.Query().Get("month"), | |
r.URL.Query().Get("day"), | |
) | |
date, err := time.Parse("2006-01-02", dateStr) | |
if err != nil { | |
return fmt.Errorf("invalid date %s", dateStr) | |
} | |
myParams.Date = date | |
myParams.Name = r.URL.Query().Get("name") | |
return nil | |
} | |
type QueryParams struct{} | |
func (q QueryParams) String(r *http.Request, name string) string { | |
return r.URL.Query().Get(name) | |
} | |
type MyExtractor struct { | |
Params | |
} | |
func (MyExtractor) DateFromQuery(r *http.Request) (time.Time, error) { | |
dateStr := fmt.Sprintf( | |
"%s-%s-%s", | |
r.URL.Query().Get("year"), | |
r.URL.Query().Get("month"), | |
r.URL.Query().Get("day"), | |
) | |
date, err := time.Parse("2006-01-02", dateStr) | |
if err != nil { | |
return time.Time{}, fmt.Errorf("invalid date %s", dateStr) | |
} | |
return date, nil | |
} | |
type MyParams struct { | |
Name string | |
Date time.Time | |
} | |
func main() { | |
req, _ := http.NewRequest("GET", "/?name=Claudemiro&year=2018&month=05&day=01", nil) | |
myParams := MyParams{} | |
binder := ParamsBinder{} | |
if err := binder.Bind(req, &myParams); err != nil { | |
panic(err) | |
} | |
m := MyExtractor{QueryParams{}} | |
fmt.Println(m.String(req, "name")) | |
fmt.Println(m.DateFromQuery(req)) | |
fmt.Println(myParams.Name) | |
fmt.Println(myParams.Date) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment