Skip to content

Instantly share code, notes, and snippets.

@im7mortal
Created September 25, 2015 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save im7mortal/67584280fb16814af2a1 to your computer and use it in GitHub Desktop.
Save im7mortal/67584280fb16814af2a1 to your computer and use it in GitHub Desktop.
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