Created
September 25, 2015 05:28
-
-
Save im7mortal/67584280fb16814af2a1 to your computer and use it in GitHub Desktop.
more go
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 ( | |
"log" | |
"net/http" | |
"os" | |
"database/sql" | |
_ "github.com/lib/pq" | |
"fmt" | |
"encoding/json" | |
) | |
type Message struct { | |
Name []string | |
} | |
func main() { | |
port := os.Getenv("PORT") | |
port = "3000" | |
if port == "" { | |
log.Fatal("$PORT must be set") | |
} | |
http.HandleFunc("/", foo) | |
http.ListenAndServe(":3000", nil) | |
} | |
func foo(w http.ResponseWriter, r *http.Request) { | |
db, err := sql.Open("postgres", "user=postgres dbname=postgres password=pol" ) | |
if err != nil { | |
log.Fatal(err) | |
} | |
rows, err := db.Query("SELECT text FROM messages ") | |
defer rows.Close() | |
if err != nil { | |
log.Fatal(err) | |
} | |
m := []string{} | |
for rows.Next() { | |
var text string | |
err = rows.Scan(&text) | |
m = append(m , text) | |
fmt.Print(text + "\n") | |
} | |
n := Message{m} | |
b, err := json.Marshal(n) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
w.Header().Set("Content-Type", "application/json; charset=utf-8") | |
w.Write(b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment