Last active
August 29, 2015 14:22
-
-
Save tejo/4e3acc5abaa141df09b0 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" | |
"log" | |
"net/http" | |
_ "github.com/go-sql-driver/mysql" | |
"github.com/gorilla/pat" | |
) | |
var db *sql.DB | |
type Repo struct { | |
Name string `json:"name"` | |
HTMLURL string `json:"html_url"` | |
URL string `json:"url"` | |
} | |
type Commits []struct { | |
Sha string `json:"sha"` | |
Commit struct { | |
Author struct { | |
Name string `json:"name"` | |
Email string `json:"email"` | |
Date time.Time `json:"date"` | |
} `json:"author"` | |
Committer struct { | |
Name string `json:"name"` | |
Email string `json:"email"` | |
Date time.Time `json:"date"` | |
} `json:"committer"` | |
Message string `json:"message"` | |
} `json:"commit"` | |
} | |
func main() { | |
var err error | |
db, err = sql.Open("mysql", "root:@tcp(:3306)/test") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer db.Close() | |
_, err = db.Exec("CREATE TABLE IF NOT EXISTS test.users(username varchar(50))") | |
if err != nil { | |
log.Fatal(err) | |
} | |
p := pat.New() | |
p.Post("/", userHandler) | |
p.Get("/{username}", fetchReposHandler) | |
http.Handle("/", p) | |
log.Fatal(http.ListenAndServe(":8000", nil)) | |
} | |
func userHandler(w http.ResponseWriter, r *http.Request) { | |
username := r.FormValue("username") | |
if username == "" { | |
w.WriteHeader(http.StatusBadRequest) | |
return | |
} | |
_, err := db.Exec("INSERT INTO test.users(username) VALUES(?)", username) | |
if err != nil { | |
log.Fatal(err) | |
w.WriteHeader(http.StatusInternalServerError) | |
return | |
} | |
log.Printf("inserted %s", username) | |
w.Header().Set("Content-Type", "text/html; charset=utf-8") | |
w.WriteHeader(http.StatusOK) | |
} | |
func fetchReposHandler(w http.ResponseWriter, r *http.Request) { | |
username := r.URL.Query().Get(":username") | |
rows, err := db.Query("SELECT * FROM test.users where username = ? LIMIT 1", username) | |
if err != nil { | |
log.Fatal(err) | |
} | |
for rows.Next() { | |
var s string | |
err = rows.Scan(&s) | |
if err != nil { | |
log.Fatal(err) | |
} | |
//username found | |
// fetch repos | |
// GET /repos/:owner/:repo/commits | |
} | |
rows.Close() | |
w.Header().Set("Content-Type", "text/html; charset=utf-8") | |
w.WriteHeader(http.StatusOK) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment