Go web API:
Rails (Rails 4, Ruby 2.0, production mode, puma web server):
Memory usage: 117MBs
Benchmarks by Matt Aimonetti
Robert Griesemer, Ken Thompson, and Rob Pike
Go 1.4
SublimeText 3
+
GoSublime
Postgresapp
Mongohub
Development Tools
22 in Total
func getPort() string {
var port = os.Getenv("PORT")
// Set a default port if there is nothing in the environment
if port == "" {
port = "4747"
}
return ":" + port
}
func main() {
engine := gin.Default()
gin.SetMode(gin.ReleaseMode)
// pushing routes
pushRoutes(engine)
log.Println("Starting server", getPort())
// start http server
engine.Run(getPort())
}
func UserLogin(c *gin.Context) {
c.AddHeader("Access-Control-Allow-Origin", "*")
var bodyMap map[string]interface{}
c.Bind(&bodyMap)
log.Println(bodyMap)
user, err := models.AuthenticateUser
(bodyMap["email"].(string), bodyMap["password"].(string))
if err != nil {
c.JSON(http.StatusUnauthorized,
gin.H{"success": false, "message": "Email/Password is wrong"})
return
}
if !user.IsActivated {
c.JSON(http.StatusUnauthorized,
gin.H{"success": false,
"message": "User is not activated yet !!\nPlease check your Email"})
return
}
c.JSON(http.StatusOK,
gin.H{"success": true, "session_key": user.SessionKey, "user": user})
}
Command godep helps build packages reproducibly by fixing their dependencies.
// to save your current dependecies
godep save
// on updating dependecies
godep update
// to restore the dependecies
godep restore
Highly recommended as Golang libraries are cutting edge and some of the changes might break your webapp, so always remain faithful to library versions unless you are sure about not getting caught naked !!
Don't confuse it with ORM, and don't worry Golang has plenty of ORM solutions
Golang also has drivers for elastic search
Object-relational mapping (ORM, O/RM, and O/R mapping) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.
Its crap
ORM means I don't have to write SQL :D
If you consider features of GORM wins single handedly. I have used it for almost 3 projects, and it really really works
// get apk with id
err := db.DB().Model(Apk{}).Where("id = ?", app.BuildId).Find(&apk).Error
// get list of apps for account with accountId and in descending order of updated_at
err := db.Where(App{AccountId: accountId}).Order("updated_at desc").Find(&apps).Error
// find IPhoneDeviceRegistration for device id and app id
err := db.DB().Model(IPhoneDeviceRegistration{}).Where("device_id = ? and app_id = ?"
,deviceId, appId).Find(®istration).Error
func PerformMigrations(db *gorm.DB) {
log.Println("Running migrations")
initial("init", db)
second("removed gcm_id and app_id from device table
and added new registration entry", db)
third("added apk_version_name column so as to track the live exceptions", db)
fourth("added logcat to the exception", db)
fifth("adding new ipa and ios device", db)
sixth("added device name in ios device struct", db)
seventh("added iphone device registration struct", db)
}
func initial(name string, db *gorm.DB) {
// this is obvious
db.AutoMigrate(&models.Migration{})
if models.IsMigrationApplied(name) {
log.Println("Migration", name, "is already applied")
return
}
log.Println("Applying", name)
db.DropTable(&models.Account{})
db.AutoMigrate(&models.Account{})
db.DropTable(&models.User{})
db.AutoMigrate(&models.User{})
db.DropTable(&models.App{})
db.AutoMigrate(&models.App{})
db.DropTable(&models.Apk{})
db.AutoMigrate(&models.Apk{})
db.DropTable(&models.AndroidDevice{})
db.AutoMigrate(&models.AndroidDevice{})
db.DropTable(&models.InviteRequest{})
db.AutoMigrate(&models.InviteRequest{})
db.DropTable(&models.AndroidException{})
db.AutoMigrate(&models.AndroidException{})
err := models.MigrationApplied(name)
if err != nil {
panic(err)
}
log.Println("Migration", name, "is applied")
}
func second(name string, db *gorm.DB) {
Depends upon how do you want migrations to work
type User struct {
Id int `json:"user_id"`
AuthKey string `json:"-" sql:"not null;unique"`
IsActivated bool `json:"is_activated"`
IsSessionKeyStale bool `json:"-"`
SessionKey string `json:"-"`
Name string `json:"user_name" sql:"not null;"`
EmailAddress string `json:"email_address" sql:"not null;"`
Password string `json:"-" sql:"not null"`
AccountId int `json:"account_id" sql:"not null;"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt time.Time `json:"deleted_at"`
}
Go has inbuilt JSON support (RFC 4627). (encoding/json)
....
app.BuildId = ipa.Id
err = app.Save()
if err != nil {
handleError(c, err)
return
}
// sending push notifications to all the devices if GCM id is available
go func(app *models.App) {
deviceRegistrations, err := models.GetDeviceRegistrationsForAppId(app.Id)
if err != nil {
log.Println(err.Error())
return
}
payload := make(map[string]interface{})
payload["make"] = "dist-1234"
payload["path"] = fmt.Sprintf("/app/%d/ipa", app.Id)
payload["name"] = app.AppName
payload["ver"] = app.Ipa.BundleVersion
for _, deviceRegistration := range deviceRegistrations {
gcm.SendMessage(1, deviceRegistration.GcmId,
"<id>", payload)
}
}(app)
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Apk is uploaded succesfully"})
The most simple asynchronous task APIs
# akshay at Akshays-MacBook-Pro.local in ~/CodeBase/distribute/src/distribute on git:master x [12:23:33]
$ gin run
[gin] listening on port 3000
[gin] ERROR! Build failed.
# distribute/controllers
controllers/appController.go:312: syntax error: nested func not allowed
[gin] Build Successful
Gin (not the framework!) (https://github.com/codegangsta/gin)
Almost any service that
has REST API
BugSnag
AirBrake
Sentry
Golang is awesome, and there is awesome-go
https://github.com/avelino/awesome-go
akshay@rainingclouds.com
RainingClouds is hiring Golang developers. Please mail us at : ping@rainingclouds.com