KalyanChakravarthy.net

Thoughts, stories and ideas.

Getting started with a blank iOS Project

Everytime I start a new Xcode/iOS project, there are few rituals I perform, quite religiously.

Disable Storyboards

I dislike storyboards and xibs with passion. Fiddling around a clunky Xcode interface to get layouts to work, with uncertainty of how they will behave on different resolutions, is quite annoying. And in large team settings which I worked in before, its quite frankly useless.

What's needed for doing it?

  1. Delete files Main.storyboard and Main-iPad.storyboard
  2. Delete the "Main Interface" setting found in
    -> Project Settings -> Targets (select) -> General -> Deployment Info -> Main Interface.

Setup the AppDelegate

Now that the storyboards are gone, we need to configure the app delegate as to what view controller is to be shown

I often end up doing this

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Instantiate the VC    
    MainViewController *vc = [MainViewController new];
    // Instantiate the navigation bar
    UINavigationController *nav = [UINavigationController alloc] initWithRootViewController:vc];

    // Instantiate window
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    // Set the root vc
    self.window.rootViewController = nav;

    // make the window visible
    [self.window makeKeyAndVisible];
    return YES;
}

Solid UINavigationBar

I find the the default navigation bar that comes along with translucent background useless. Majority of all apps end up either with a solid color or a subtle gradient.

Sometimes I prefer to subclass UINavigationController and other times, I just configure it directly. Either case the essential snippet of code is this:

// Disable translucency 
navViewController.navigationBar.translucent = NO;  
// Set it to something jazzy
navViewController.navigationBar.barTintColor = [UIColor orangeColor];  

Setup MainViewController

When a view controller is added to a UINavigationController stack, it doesn't flow from below the navigation bar, but from underneath it (from iOS 7~). This again seems quite pointless.

The sane default I follow is to set the edgesForExtendedLayout property

MainViewController -viewDidLoad

self.edgesForExtendedLayout = UIRectEdgeNone;  

Misc

Auto Layout: Although it tends to be more verbose, I prefer writing code that declares how interface objects look and behave proportional to the screen size, than use Storyboards or XIBs.

Manual Layout: Sometimes I don't mind setting the frames manually for simpler things.

Libraries: Most times I end up adding these as well

  • Flurry and Google analytics for analytics/tracking
  • Additional classes to enable use of a file based, simple key value store.
  • Shorthand functions Eg: UIColor* RGBColor(r,g,b)
  • UI Utilities that allow me to do this view.top = 20;

More on these later.

Go-snippet: static file server

Am working on building some tooling that involves cloning a git repository and passing its path to my go server. One of the duties of that server is to make a static files folder available at a specific path.

This is the code snippet I use to achieve it.

r := mux.NewRouter() //gorilla mux  
r.PathPrefix("/static").Handler(  
   http.StripPrefix(
     "/static/", 
     http.FileServer(http.Dir("./static-dir/"),
   ),
)
http.Handle("/", r)  
http.ListenAndServe(":8080", nil)  

Note: The comma at end of each line, including at the end of http.StripPrefix call, is required; otherwise go compiler complains of bad syntax. Using commas to enable splitting statements into multiple lines feels a little ridiculous.

TLS webserver server in Go

Simple HTTP Server

Getting a go webserver is incredibly simple. All it takes is this

mux := http.NewServeMux()  
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request)  
s := &http.Server{  
    Addr: ":8080",
    Handle: mux,
}
s.ListenAndServe()  

TLS Server

If all you wanted was to run it with single certificate pair, its straight forward

s.ListenAndServeTLS("certFile", "keyFile")  

TLS Server with multiple certificates

Default server.ListenAndServe is not good for running an http server with multiple certificates.

This was a particular use case I needed to solve

Now why would you want to do that?

  • Its needed for running single server for multiple domains having different certificates.
  • Public certificate for user and other private set of certificates for external or third-party services.
  • A secondary certificate as backup when primary one expires.

Achieving this with custom certificates is a bit more tricky. Here are the steps:

First, setup TLS config

tlsConfig := &tls.Config{  
    NextProtos:               []string{"http/1.1"},
    MinVersion:               tls.VersionTLS10,
    SessionTicketsDisabled:   true,
    PreferServerCipherSuites: true,
}

Load certificate pairs

certPair, err := tls.LoadX509KeyPair("cert", "key")  
tlsConfig.Certificates = []tlsConfig.Certificates{ certPair }

Build name to certificate mapping

tlsConfig.BuildNameToCertificate()  

Create the server object and start it

tlsServer := &http.Server{  
Addr:         "0.0.0.0:8080",  
    Handler:      myHandler,
    TLSConfig:    tlsConfig,
    TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
}

tlsServer.ListenAndServe()  

TLS with letsencrypt

Go's nifty crypto library is built with letsencrypt's ACME (Automated Certificate Management Environment) protocol in mind.

more information about it is here - https://kalyanchakravarthy.net/blog/https-server-with-go-letsencrypt/

HTTPS server with Go + LetsEncrypt

Getting a HTTPS server started in Go using certificates from letsencrypt is incredibly easy. Just takes 3 lines of code.

Usage

The package autocert does this for you.

go get -d golang.org/x/crypto/acme/autocert  

Use it to constructs a new listener and start a server

l := autocert.NewListener("www.example.com)  
s := &http.Server{}  
s.Serve(l)  

Full Source

package main

import (  
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
    "golang.org/x/crypto/acme/autocert"
)

func main() {  
    // 1. proxy requests
    // 2. letsencrypt based https
    // 3. read-only mode

    addr := "kalyanchakravarthy.net"

    m := mux.NewRouter()
    m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(200)
        fmt.Fprintf(w, "Hello world")
    })

    s := &http.Server{
        Handler: m,
    }

    l := autocert.NewListener(addr)

    s.Serve(l)
}

Books in 2016

A better part of 2016 was spent reading books. This obsession took shape from the company of people who liked to read, in a country where there was nothing much I could do offline without getting overwhelmed; nor could I wander around online without ultra-slow-vpns (aka China). One goal for 2016 was to finish reading atleast 25 book and I managed to reach it. A major chunk was filled by Sci-Fi.

Here are those in reverse chronological order

  1. The Martian
    Andy Weir
  2. Beacon 23: The complete Novel
    Hugh Howey
  3. Rendezvous with Rama
    Arthur C Clarke
  4. Speaker For The Dead (Ender Saga - Book 2)
    Orson Scott Card
  5. Enders Game (Ender Saga - Book 1)
    Orson Scott Card
  6. Redshirts
    John Scalzi
  7. The Last Colony (Old Man's War - Book 3)
    John Scalzi
  8. Earth Rising (Earthrise Book 3)
    Daniel Arenson
  9. Earth Lost (Earthrise Book 2)
    Daniel Arenson
  10. Earth Alone (Earthrise Book 1)
    Daniel Arenson
  11. Half Way Home
    Hugh Howey
  12. The Ghost Brigades (Old Man's War - Book 2)
    John Scalzi
  13. Old Man's War (Book 1)
    John Scalzi
  14. The Checklist Manifesto
    Atul Gawande
  15. Dust (Silo Series - Book 3)
    Hugh Howey
  16. Shift(Silo Series - Book 2)
    Hugh Howey
  17. Wool (Silo Series - Book 1)
    Hugh Howey
  18. Green Mars (Mars Trilogy - Book 3)
    Kim Stanley Robinson
  19. The Rosie Project: Don Tillman
    Graeme Simsion
  20. Blue Mars (Mars Trilogy - Book 2)
    Kim Stanley Robinson
  21. Thunder Below: The USS Barb
    Eugene B. Fluckey
  22. Red Mars ( Mars Trilogy - Book 1)
    Kim Stanley Robinson
  23. Elon Musk
    Ashlee Vance
  24. Not A Penny More, Not A Penny Less
    Jeffrey Archer
  25. The Hitchhiker's Guide to the Galaxy
    Douglas Adams