“fmt” “net/http” ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, “hello world!”) } func main() { http.HandleFunc(“/”, handler) http.ListenAndServe(“:8080”, nil) } Local server connecIon Handler funcIon when root is requested Print output to client All executable commands use package main Go’s stdlib Entry point
func ReadStatus() (res [][]string) { err := db.Ping() if err != nil { log.Fatal(err) } rows, err := db.Query("SELECT id, tweet, username FROM posts WHERE username = ? ORDER BY id DESC", currentuser) if err != nil { log.Fatal(err) } defer rows.Close() var tweet, id, username string for rows.Next() { err := rows.Scan(&id, &tweet, &username) if err != nil { return res } var a []string a = append(a, id, tweet, username) res = append(res, a) } return }
func ReadStatus() (res [][]string) { err := db.Ping() if err != nil { log.Fatal(err) } rows, err := db.Query("SELECT id, tweet, username FROM posts WHERE username = ? ORDER BY id DESC", currentuser) if err != nil { log.Fatal(err) } defer rows.Close() var tweet, id, username string for rows.Next() { err := rows.Scan(&id, &tweet, &username) if err != nil { return res } var a []string a = append(a, id, tweet, username) res = append(res, a) } return } Verify db connecIon Raw queries Append strings to slice Append slice of strings to output
Posts slice func homeHandler(w http.ResponseWriter, r *http.Request) { currentuser = getUserName(r) if currentuser != "" { var as []Post a := User{} m := ReadStatus() for i := 0; i < len(m); i++ { as = append(as, Post{Tweetid: m[i][0], Username: currentuser, Status: m[i][1]}) } a = User{Username: currentuser} for i := 0; i < len(m); i++ { a.Posts = append(a.Posts, &as[i]) } renderTemplate(w, "home", "homepage", a) } else { http.Redirect(w, r, "/", 302) } } Wrapper func around html/template library Create slice with Post instances