Created
August 13, 2014 13:35
-
-
Save leehambley/68b47124bc54dd4aaede 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
| CREATE DATABASE tt; | |
| \c tt | |
| CREATE TABLE widgets ( | |
| id INT PRIMARY KEY NOT NULL, | |
| name TEXT NOT NULL | |
| ); | |
| INSERT INTO widgets (id, name) VALUES (456, 'AeroPress'); |
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" | |
| "fmt" | |
| "log" | |
| "net/http" | |
| "strconv" | |
| _ "github.com/lib/pq" | |
| ) | |
| const pgSqlDsn = "dbname=tt sslmode=disable" | |
| func main() { | |
| mux := http.NewServeMux() | |
| mux.HandleFunc("/foo", FooHandler) | |
| err := http.ListenAndServe(":3000", mux) | |
| if err != nil { | |
| log.Fatalf("Couldn't start server: %v\n", err) | |
| } else { | |
| log.Println("Listening...") | |
| } | |
| } | |
| func FooHandler(w http.ResponseWriter, req *http.Request) { | |
| var widgetName string | |
| widgetIdStr := req.FormValue("id") | |
| widgetId, err := strconv.ParseInt(widgetIdStr, 10, 0) | |
| if err != nil { | |
| w.WriteHeader(http.StatusBadRequest) | |
| if len(widgetIdStr) == 0 { | |
| widgetIdStr = "(empty)" | |
| } | |
| fmt.Fprintf(w, "`%s' is not a valid widget ID\n", widgetIdStr) | |
| return | |
| } | |
| db, err := sql.Open("postgres", pgSqlDsn) | |
| if err != nil { | |
| log.Fatalf("Error opening database handle: %s\n", err) | |
| } | |
| err = db.QueryRow("SELECT name FROM widgets WHERE id = $1", widgetId).Scan(&widgetName) | |
| switch { | |
| case err == sql.ErrNoRows: | |
| w.WriteHeader(http.StatusNotFound) | |
| fmt.Fprintf(w, "No widget with ID %d\n", widgetId) | |
| case err != nil: | |
| w.WriteHeader(http.StatusInternalServerError) | |
| fmt.Fprintf(w, http.StatusText(http.StatusInternalServerError), widgetId) | |
| log.Fatalf("Database Error:", err) | |
| default: | |
| fmt.Fprintf(w, "Widget Name: %s\n", widgetName) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment