Thursday, August 22, 2013

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

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 (
    _ ""

func main() {
    // GoREST usage: http://localhost:8181/tutorial/hello
    gorest.RegisterService(new(Tutorial)) //Register our service

//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) + ");")

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.)


1 comment:

Larry said...

I think there's a syntax error.
The db part should be this.

`db.Exec("INSERT INTO table (number) VALUES(" + strconv.Itoa(number) + ");")`