Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
more go
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