Created
September 3, 2012 19:21
-
-
Save collinvandyck/3612586 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 ( | |
| "database/sql" | |
| "fmt" | |
| "time" | |
| ) | |
| type User struct { | |
| Id string | |
| Email string | |
| CreatedAt time.Time | |
| UpdatedAt time.Time | |
| Name string | |
| Admin bool | |
| Active bool | |
| } | |
| func GetUserByApiKey(key string) (*User, error) { | |
| fmt.Printf("Getting user with API key %s\n", key) | |
| db, err := sql.Open("postgres", "...") | |
| if err != nil { | |
| return nil, err | |
| } | |
| defer db.Close() | |
| rows, err := db.Query("select id, email, created_at, updated_at, name, admin, active from users where apikey = $1", key) | |
| if err != nil { | |
| return nil, err | |
| } | |
| if rows.Next() { | |
| // I have to declare byte slices to account for null DB values | |
| var id []byte | |
| var email []byte | |
| var createdAt time.Time | |
| var updatedAt time.Time | |
| var name []byte | |
| var admin bool | |
| var active bool | |
| err = rows.Scan(&id, &email, &createdAt, &updatedAt, &name, &admin, &active) | |
| if err != nil { | |
| return nil, err | |
| } | |
| // when I build my User struct, I convert the byte slices to string values | |
| user := User{ | |
| Id: string(id), | |
| Email: string(email), | |
| CreatedAt: createdAt, | |
| UpdatedAt: updatedAt, | |
| Name: string(name), | |
| Admin: admin, | |
| Active: active} | |
| fmt.Printf("Made a user: %#v\n", user) | |
| return &user, nil | |
| } | |
| return nil, nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment