舫摘

知人者智 自知者明 胜人者有力 自胜者强

0%

Build a RESTful API with Golang


In this tutorial, I will illustrate how you can build your own RESTful API in Golang. All the code used in this demo can be found on my Github.

Before start

We need to set up our environment to start up writing our API.
You can get the Latest Release of Go (as of this writing, it’s 1.10.2 ) > here
Once you’ve installed Golang, you should set a sys variable named $GOPATH.
Check here for more details.

Install Package Manager

Package Manager is a useful tool for cooperation. It’s making sure you and others developers whose work on the same team using exactly the same version packages.
There are kinds of package manager in golang, I choose dep in this tutorial.
To install it just run “brew install dep” in mac. For others operation system please check document on Github.

Initialization Project

Before writing API, we need to create a directory for put the source code.

  • Run the command below in a command line
    1
    mkdir -p $GOPATH/src/github.com/k9982874/golang-api-service-sample
  • Switch the working directory
    1
    cd $GOPATH/src/github.com/k9982874/golang-api-service-sample
  • Initialization
    1
    def init
    The directory structure should look like below

Install Web Frame Work

Almost there. Let’s install a web framework.
Same as Package Manager there is a lot of web framework we can use. I choose Gin in this tutorial. My favorite one.
Let’s open the file Gopkg.toml and add three new lines at end of the file.

1
2
3
[[constraint]]
name = "github.com/gin-gonic/gin"
revision = "bf7803815b0baa22ff7a10457932882dfbf09925"

The reason why don’t use the stable version is the stable version of Gin missing a method called ShouldBindJSON. We need it transform the JSON data into a struct.

Write API

Finally, we start writing the first API.

  • Create a directory named controllers. All controllers have gone be putting in here.

  • Create a file named base.go and put it into controllers directory.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    package controllers

    import (
    "net/http"

    "github.com/gin-gonic/gin"
    )

    type IController interface {
    Get(c *gin.Context)
    Post(c *gin.Context)
    Put(c *gin.Context)
    Delete(c *gin.Context)
    }

    type Base struct {
    }

    func (self *Base) Ok(c *gin.Context) {
    payload := gin.H{
    "code": http.StatusOK,
    "message": http.StatusText(http.StatusOK),
    }
    c.JSON(http.StatusOK, payload)
    }

    func (self *Base) Json(c *gin.Context, data interface{}) {
    payload := gin.H{
    "code": http.StatusOK,
    "message": http.StatusText(http.StatusOK),
    "data": data,
    }
    c.JSON(http.StatusOK, payload)
    }

    func (self *Base) Error(c *gin.Context, code int) {
    payload := gin.H{
    "code": code,
    "message": http.StatusText(code),
    }
    c.JSON(http.StatusBadRequest, payload)
    }

    func (self *Base) Get(c *gin.Context) {
    self.Error(c, http.StatusNotImplemented)
    }

    func (self *Base) Post(c *gin.Context) {
    self.Error(c, http.StatusNotImplemented)
    }

    func (self *Base) Put(c *gin.Context) {
    self.Error(c, http.StatusNotImplemented)
    }

    func (self *Base) Delete(c *gin.Context) {
    self.Error(c, http.StatusNotImplemented)
    }

    We defined an interface which has 4 methods named IController, a struct implemented those methods named Base.
    All the controllers should inherit Base struct.

  • Create the first controller application.so in controllers directory.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    package controllers

    import (
    "github.com/gin-gonic/gin"
    )

    type Application struct {
    Base
    }

    func NewApplicationController(r *gin.Engine) IController {
    app := new(Application)

    rg := r.Group("/api/app")
    rg.GET("/", app.Get)

    return app
    }

    func (self *Application) Get(c *gin.Context) {
    self.Ok(c)
    }

    We defined another struct called Application. It’s inherited Base struct and override Get method. It’s handle requests from client and responds a success message.

  • At last, create an entry file named main.go in the root directory of the project.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    package main

    import (
    "github.com/gin-gonic/gin"
    controllers "github.com/k9982874/golang-api-service-sample/controllers"
    )

    func main() {
    r := gin.Default()

    controllers.NewApplicationController(r)

    r.Run(":9999")
    }

Launch!

All is set and We are ready!

  • Compile project
    Run the command below in a command line
    1
    go build
    After this, you can find a new file named golang-api-service-sample in the root directory of the project. It’s a binary file what we compiled.
  • Run! Run! Run!
    1
    ./golang-api-service-sample
    Run the command above in a command line, you should get output like below.

    Obviously, we got an API service running at port 9999.
    Awesome!

Test the API service

Open your favorite browser and fill localhost:9999/api/app into the address bar. You should get the result like below.

In this tutorial, we learned how to create an API service which has a router to handle the request came from clients.

Hope you guys and girls enjoyed reading this as much as I enjoyed writing it. Have fun.