Go Examples

HTTP Server in GO

package main

import (
  "net/http"
  "log"
)

type Options struct {
  Path string
  Port string
}

func main() {

  op := &Options{Path: "./", Port: "8001"}

  http.Handle("/", http.FileServer(http.Dir(op.path)))
  err := http.ListenAndServe(":" + op.port, nil)
  if err != nil {
    log.Fatal("ListenAndServe: ", err)
  }
}

JSON Parsing in Go

This is useful for config files, etc.

package main

import (
  "encoding/json"
  "io/ioutil"
)

type Options struct {
  Path string
  Port string
}

func main() {

  // set default options
  op := &Options{Path: "./", Port: "8001"}

  // read config file into memory
  data, _ := ioutil.ReadFile("./config.json")

  // parse config file, store results in "op"
  json.Unmarshal(data, op)

  log.Println("Parsed options from config file: ", op)
}

RPC in Go

Go has a generic RPC interface which can be used with any protocol.  JSON-RPC and "gobs" are supported natively.  You can expose RPC methods like this:

package main

import (
  "rpc"
  "os"
  "net/http"    
)

type Args struct {
   A, B int
}

type Results struct {
   X int
}

type RPCMethods struct {
  // just an empty struct
}

// this is an RPC method
func (m *RPCMethods) Multiply (args Args, results *Results) error {
  *results.X = args.A * args.B
  return nil  // no error
}

func main () {
  // expose methods of RPCMethods instance
  rpc.Register(&RPCMethods{})

  // start server
  rpc.HandleHTTP()
  http.ListenAndServe(":12345", nil)
}

You can test your RPC server by pointing a browser at http://localhost:12345/debug/rpc, which should list all the registered RPC methods.

To communicate with your server, you can write a client like this:

package main

import (
"net/rpc"
"fmt"
)

type Args struct {
A, B int
}

type Results struct {
    X int
}

func main () {

client, _ := rpc.DialHTTP("tcp", "localhost:12345")

var results Results
client.Call("RPCMethods.Multiply", Args{1, 2}, &results)

fmt.Println("results: ", results)
}

More details here: http://golang.org/pkg/net/rpc/

Marshaling JSON from Objects

"Marshaling" is the process of serializing an object into a wire format such as JSON.  Go excels at this task.

package main

import (
  "encoding/json"
  "fmt"
)

type Person struct {
  // exported fields must be Uppercase
  Name string
  Age int
}

func main () {

   ryanne := &Person{"Ryanne", 25}
   wire, _ := json.Marshal(ryanne)
   fmt.Println(string(wire))
}


REST APIs in Go


package main

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

type Person struct {
Name string
Age int
}

var ryanne Person


func ryanneHandler(w http.ResponseWriter, req *http.Request) {

switch req.Method {
case "GET":
        buf, _ := json.Marshal(&ryanne)
        w.Write(buf)
case "PUT":
buf, _ := ioutil.ReadAll(req.Body())
json.Unmarshal(buf, &ryanne)
default:
w.WriteHeader(400)
}
}

func main () {

ryanne.Name = "Ryanne"
ryanne.Age = 25

http.HandleFunc("/ryanne", ryanneHandler)
http.ListenAndServe(":8003", nil)
}



MongoDB in Go with mgo

You can install mgo with the following command:

go install launchpad.net/mgo

Documentation is here: http://labix.org/mgo

s, err := mgo.Mongo("localhost")
defer s.Close()

c := s.DB("test").C("users")

person := &Person{Name: "Ryanne", Age: 28}
c.Insert(person)

person2 := bson.M{"Name": "Ryanne", "Age" : 28}
c.Insert(person2)

var result Person
iter := c.Find(query).Iter()
for iter.Next(&result) {
   fmt.Println(result)
}






Comments