Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Tag: c#

Creating a Microservice in Go

A while back (like, quite a while) I started playing with Go and then unfortunate circumstances kept me from continuing my exploration. My recent exposure to super brilliant people has rekindled some of my desire to explore new languages. Since I’ve been knee-deep in microservices recently, I decided to try and build a microservice in Go.

There are a number of libraries available to Go developers that help with this kind of thing (including Martini). But, I want to see what it looks like to build the most minimal microservice possible. Turns out, that’s pretty damn minimal:

package main

import (
 "encoding/json"
 "net/http"
)

func main() {
 http.HandleFunc("/zombie/", zombie)
 http.ListenAndServe(":8080", nil)
}

type ZombieThing struct {
 Text string
 Name string
 Age int
}

func zombie (w http.ResponseWriter, r *http.Request) {
  zomb := ZombieThing {"Watch out for this guy!", "Bob Zombie", 12}
  b, err := json.Marshal(zomb)
  if err != nil {
    panic(err)
  }
  w.Write(b)
}

So now I just type go run service.go and the service is running. Now I can just curl the service:

$ curl http://localhost:8080/zombie/
 {"Text":"Watch out for this guy!","Name":"Bob Zombie","Age":12}

If you’re wondering why I used upper-case member names for the JSON object being returned, it’s because I’m lazy. Go considers a variable name with lower case to be private or non-exported, so if I were to make the ZombieThing struct have lowercase names, nothing would be exported and the service would return {}.

So, basically we have yet another example in a long list of examples proving that microservices are a language-agnostic architecture and you can build them in pretty much whatever language and framework that suits your needs.

First Impressions of the Go Language

I recently got a chance to hang out with some very brilliant people and one of the guys mentioned how fond he was of Go, a programming language most commonly associated with Google. To be honest, the fact that it was “yet another thing that came out of Google” is exactly why I hadn’t played with it up until this point. I’d seen a few blog posts but skimmed them. This time, however, I decided to give Go a more fair shake and so I downloaded it and started hacking away. What happened next shocked even me.

I’m not a coding newb, but even I know that there’s a learning curve to each language and recently the learning curves have been getting steeper – Scala and Clojure come to mind, as well as some of the UI frameworks that aren’t languages, but they have language-sized learning curves (AngularJS is the 800 pound gorilla of learning curves). That’s why when I had ‘Hello World’ compiled and running in about 12 minutes after my first click on golang.org, I was shocked.

If you are unfamiliar with Go, it takes a little getting used to because at first glance it seems like a hodgepodge of some features you would never expect to see in the same language. Here’s a quick list that I found over on this blog post entitled Why Go?:

  • Asynchronous – We’re all about reactive programming these days and all the hip kids are building non-blocking, asynchronous code. In fact, if I hear one more Node.js zealot shout “it’s non-blocking” one more time, I will stab him in the face with a web socket. Go has these things called Goroutines that are lightweight async execution blocks and they have channels that make my inner Erlang and Akka fanboy giggle. Bottom line is you write synchronous-looking code but it’s non-blocking and there are no callbacks. Callback hell needs to be avoided at all costs.
  • Concurrency – Paired with the asynchronous support features and support for multi-core with channels is very appealing, especially considering some of the other aspects of the language (check out the next bullet, you’re going to crap yourself)
  • Static Binaries – Oh that’s right. There’s no JVM. There’s no VM of any kind. You don’t have to wait for a runtime to go dig through classpath garbage and dynamically load a hojillion JAR files. These are compilednative binaries. Remember way back in the good old days when you could just pass around and executable and that worked?? Yeah, I had almost forgotten those times as well.
  • Language Features – In addition to looking like C, having asynchronous, actor-like support for concurrency and parallel programming, it also has a lot of the goodies that people think you can only get from some of the newer JVM or functional languages  like type inference and my personal favorite, implicitly satisfied interfaces … wait wait.. it gets better… the implicitly satisfied interfaces are checked and satisfied at compile-time… I almost shed a tear when I saw that.
  • Privacy indicated via case, not keywords – Capital lettered members are exported, lowercase ones are not.
  • Imperative, object-oriented language – You’d think this is contradictory, but with Go it just seems to work. I was very skeptical until I started playing with it. Go doesn’t have classes, yet it supports message passing via methods, polymorphism, and namespacing. Crazy, right?
  • Multiple return values – The language looks like C, but you can invoke methods that return multiple values and it looks just like a Scala unapply syntax. Me likey.

So, I sat down and I downloaded Go and got it working and followed the advice of setting up the $GOPATH environment variable that pointed to a single root under which all of my Go code would reside. It felt a little awkward, but there seemed to be some method to the madness, specifically relating to the fact that Go can fetch its dependencies directly from Github and that it can resolve transitive dependencies without the need for a make file, maven, or sbt. Holy crap – compiling to a native binary without maven or sbt? That’s cause for celebration.

So, let’s get to the hello world? (You can get the instructions to download Go and set up “Hello World” from here at golang.org.

package main

import "fmt"

func main() {
  fmt.Printf("Hello world.\n")
}

When you issue a go install command at the command line, this compiles your Go code. It doesn’t just create a JAR file or a DLL file that will be interpreted (JIT or otherwise) by a runtime like the .NET CLR or the Java Virtual Machine, it creates a static standalone self-executing binary. Ah but you say Java can create executable JARs too, right? This isn’t the same, this is a native executable whereas an executable JAR is just a regular JAR with the JVM launching bootstrapped in.

When I first sat down and started reading the docs on Go, I had mixed feelings and still do. On the one hand, it feels like a step back in that some of it looks like old school C (don’t get me wrong, I love me some old school C) whereas other parts are amazingly terse yet ridiculously powerful (channels, goroutines, slices, transitive no-makefile dependency resolution). I don’t know yet what my final thoughts are, but I know that right now it is appealing to my love of the C language (I think Go is one of the most C-pure looking syntaxes I’ve seen in a long time) with my love of Erlang, the actor pattern, and asynchronous back-end programming.

This is just hello world. If you’ve read this blog before then you know the real test I have to put Go through in order to vet it as a language and I’ll be posting a series of blog posts on that soon. The real question I ask of any new language is this: Can I create a MUD with this language?

I’m about to find out – stay tuned!

Protocol Buffers on iOS – Source Code

For those of you who have been asking for the source code to the sample I wrote some time ago illustrating how to serialize and de-serialize protocol buffer messages on the iPhone, then you can download a fully functioning sample project from here:

ProtoPhone

This contains the Xcode project file as well as all of the source code, which should hopefully get you started.

Note that this sample is really just a serialization and de-serialization sample. The code expects for there to be some socket server listening on localhost, so you will have to modify it to no longer expect that (or write your own server that receives ZombieSightinmessages).

Enjoy!

Google Protocol Buffers on iOS and Mac – Redux

In a previous blog post, I talked about how I used the C++ stock Google Protocol Buffers generated code and the native C++ library in my iOS application. It involved some trickery of creating a wrapper Objective-C++ class to keep the C++ from bleeding into my Cocoa project, I had to link a static library, and it actually bloated my application quite a bit.

Since then, I have found a great native Objective-C protobuf implementation that not only plugs into the regular protoc compiler, but it generates ARC-friendly code. Check out this library on Github for the Objective-C protobuf code.

Now, rather than fussing with creating a C++ object (which requires me to manually malloc and free!), I can just create a new protobuf object that feels natural and native to my iOS and Mac code:

ZombieSighting *sighting =
        [[[[[[[ZombieSighting builder] setDescription:@"This is a zombie"]
                setLatitude:21.007]
                setLongitude:18.214]
                setZombieType:ZombieTypeFast]
                setName:@"Lord Kevin of the Undead"] build];

With this implementation of protobufs, I can just do [sighting data] to get the NSData for the object, and I can de-serialize a protobuf object that I plucked off the wire far more easily than before:

DirectMessage *dm = [DirectMessage parseFromData:data];

See how much easier and cleaner everything is? The moral of the story here is good enough isn’t good enough. Just because you find one solution doesn’t mean it’s the best one. I am constantly in search of simpler, easier, more elegant ways of doing things and I think I’ve finally found a decent way of dealing with protobufs in Objective-C.

Is there finally a Heroku for .NET developers? AppHarbor thinks so.

If you’ve read many of my posts, especially those from my previous blog (The .NET Addict), then you’re well aware of how much I like Heroku. These guys are geniuses and the service they offer is absolutely top notch. And, by top notch, I mean, I haven’t found anyone who can offer better. People use Heroku as their go-to source for web apps and web services when they don’t want to front the infrastructure in-house. Their tiered, free-to-start pricing is absolutely ideal for independent developers who have an idea they want to build but it requires some cloud presence.

For example, think of all those iOS developers building iOS apps that need some kind of server presence or back-end to make their app work. Unless you’re a company, you probably can’t afford to stick a box in a datacenter and fire it up and do the maintenance yourself. You might go the traditional web hosting route but, you probably run into all kinds of configuration quirks and limitations. Enter Heroku. Build a Ruby on Rails site on your local machine that provides exactly the kind of back-end you need for your app and then git push your work up to Heroku. Once there, your stuff’s in the cloud.

Ok, enough about Heroku. The biggest drawback of Heroku (at least as far as many C# developers are concerned) is that it works only on Ruby on Rails and, is generally easier to access from Macs and Linux boxes than windows. Until recently, if you were a .NET developer then your only options were to go the traditional web hosting route, fire up an Amazon EC2 VM running Windows, or use Windows Azure and learn an entirely new SDK and make absolutely sure your app works nowhere but in Microsoft’s proprietary cloud.

You know what would kick ass? Heroku for .NET. It would be great if I could create a Visual Studio solution that runs and works locally, talks to local SQL databases, has unit tests that work just like my regular enterprise solutions… but then I could git push that VS solution into the cloud and then it just works.

Enter AppHarbor. These folks claim to be just that – Heroku for .NET. You can use git to push your Visual Studio 2010 solution right up to their servers. Once there, they actually will seek out and run all of the unit tests in your solution and show you the results. So now you’ve got Heroku for .NET with a little sprinkle of TeamCity and Continuous Integration thrown in for good measure.

One of the things that I love about Heroku is that I can just do a rake db:migrate and push data from my local box out to the cloud version of my application. I can do the same with an AppHarbor database – their SQL server databases are accessible directly from SQL Management Studio with SQL Server authentication. My first question is – why the hell isn’t it this easy to talk to Azure databases?? My second thought is – awesome.

If AppHarbor wants to compete with Heroku for developer mindshare, they’re going to need to provide a truckload of add-ons and plugins. If you’ve seen Heroku’s add-on page lately, you know that they have an insane amount of additional platform features that you can turn on with the flip of a switch. AppHarbor and Heroku both truly embrace the PaaS (Platform as a Service) model. The add-ons that are available at launch (which is today, actually) from AppHarbor are: MongoHQ, Cloudant, Redis, Memcacher, Mailgun, and New Relic (available next week).

AppHarbor’s infrastructure sits on top of Amazon’s infrastructure. This means that they’re basically doing all the hard work of utilizing Amazon’s virtual infrastructure, configuring the machines, partitioning things, dealing with disk space issues, clustering, load balancing – all that stuff you’d have to do if you talked directly to Amazon yourself. Coincidentally, Heroku does the same thing. Your application is really backed by Amazon’s cloud.

So, a cloud platform that allows me to create an application and git deploy to it in less than 1 minute (yes, I timed it – 42 seconds from “File -> New Project” to running on the web), gives me access to databases in the cloud (though I think their current 10MB -or- 10GB choice is a little myopic), gives me plug-ins and add-ons to add features to my virtual platform in the cloud? To quote my favorite TV personality, the Russian DirecTV guy with the miniature lap giraffe – I JUMP IN IT.

But seriously, time will tell if companies like AppHarbor are successful. One huge risk that people take when jumping into the cloud is lock-in. Nobody wants to write code for one specific cloud vendor if that cloud vendor might in the future change their platform or worse, shut down entirely. The beauty of companies like Heroku and AppHarbor is that there is no lock-in. The Ruby on Rails app that works on your Mac will work on Heroku and if Heroku burns to the ground tomorrow, heaven forbid, all that code you write is still viable elsewhere. The same goes for AppHarbor. You’re not writing code for Microsoft’s proprietary Azure Table or Queue storage – you’re hitting a SQL or mySQL server. You’re not writing code that only runs on your machine in a simulated environment that isn’t even all that good a simulator (Azure), you’re writing code that is just pure .NET that you can re-use on some other platform provider if you choose to move it, or pull it in-house if your needs change.

WP7 for iPhone and Android Developers – Introduction to C#

I’ve started a new series of articles over on Silverlightshow.net. In this series of articles I guide the reader through some of the most important aspects of Windows Phone 7 development, with an eye toward helping readers map their existing iOS and Android knowledge to C#, WP7, and Silverlight.

The first of these articles has just been published here. Head on over and give it a read, I hope you enjoy it.