Created
September 16, 2015 01:35
-
-
Save jakejscott/f679f32c9949be32d3b8 to your computer and use it in GitHub Desktop.
simple-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 ( | |
"database/sql" | |
"fmt" | |
"github.com/superlogical/simple-go/Godeps/_workspace/src/github.com/go-gorp/gorp" | |
_ "github.com/superlogical/simple-go/Godeps/_workspace/src/github.com/go-sql-driver/mysql" | |
"github.com/superlogical/simple-go/log" | |
"github.com/superlogical/simple-go/util" | |
"net/http" | |
"os" | |
"strings" | |
"time" | |
) | |
var ( | |
ip string | |
) | |
type Post struct { | |
Id int64 `db:"post_id"` | |
Created int64 | |
Title string `db:",size:50"` | |
Body string `db:"article_body,size:1024"` | |
} | |
func newPost(title, body string) Post { | |
return Post{ | |
Created: time.Now().UnixNano(), | |
Title: title, | |
Body: body, | |
} | |
} | |
func indexHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprint(w, "It works! The ip address:", ip) | |
} | |
func initDB(dbUrl string) *gorp.DbMap { | |
db, err := sql.Open("mysql", dbUrl) | |
checkErr(err, "sql.Open failed") | |
log.Info("CONNECTED=ok") | |
err = db.Ping() | |
checkErr(err, "Ping failed") | |
log.Info("PING=ok") | |
dbmap := &gorp.DbMap{ | |
Db: db, | |
Dialect: gorp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8"}, | |
} | |
dbmap.AddTableWithName(Post{}, "posts").SetKeys(true, "Id") | |
err = dbmap.CreateTablesIfNotExists() | |
checkErr(err, "Create tables failed") | |
return dbmap | |
} | |
func checkErr(err error, msg string) { | |
if err != nil { | |
log.Fatal(msg, err) | |
} | |
} | |
func main() { | |
log.Info("Starting simple-go") | |
port := os.Getenv("PORT") | |
if port == "" { | |
port = "8080" | |
} | |
log.Info("PORT=", port) | |
dbUrl := os.Getenv("DATABASE_URL") | |
log.Info("DATABASE_URL=" + dbUrl) | |
log.Info("ENV=:") | |
for _, e := range os.Environ() { | |
pair := strings.Split(e, ":") | |
log.Info(pair) | |
} | |
log.Info("CONNECTING: ", dbUrl) | |
dbmap := initDB(dbUrl) | |
defer dbmap.Db.Close() | |
ip = util.GetMyIpAddress() | |
http.HandleFunc("/", indexHandler) | |
host := "http://" + ip + ":" + port | |
log.Info("LISTENING=", host) | |
log.Fatal(http.ListenAndServe(":"+port, nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment