GoREST (golang web services) Simple Examples

In my last post, Installing GoREST on Ubuntu Linux, I mentioned that I should really post a simple example of using GoREST. Here’s some example code for a Get and Post request using GoREST web services in golang.

Note that I’m also using the go-sql-driver/mysql driver for MySQL in golang. To install the driver, simply run:

$ go get github.com/go-sql-driver/mysql

Also, this example isn’t actually using JSON. Check out the link at the end of this post for a JSON example.

package main
import (
      "code.google.com/p/gorest"
    _ "github.com/go-sql-driver/mysql"
      "database/sql"
      "net/http"
      "log"
      "time"
      "os"
      "strconv"
)

func main() {
    // GoREST usage: http://localhost:8181/tutorial/hello
    gorest.RegisterService(new(Tutorial)) //Register our service
    http.Handle("/",gorest.Handle())    
    http.ListenAndServe(":8181",nil)
}

//Service Definition
type Tutorial struct {
    gorest.RestService `root:"/tutorial/" consumes:"application/json" produces:"application/json"`
    hello  gorest.EndPoint `method:"GET" path:"/hello/" output:"string"`
    insert   gorest.EndPoint `method:"POST" path:"/insert/" postdata:"int"`
}

func(serv Tutorial) Hello() string{
    return "Hello World"
}

func(serv Tutorial) Insert(number int) {
    db, err := sql.Open("mysql", "root:password@/dbname?charset=utf8")
    db.Exec("INSERT INTO table (number) VALUES(strconv.Itoa(number) + ");")
    db.Close()
    serv.ResponseBuilder().SetResponseCode(200)
}

I’m using Postman REST Client for my post tests, you can download Postman for free from the Chrome web store. (Blog post on using Postman with JSON.)

image