start go restful api gin

start go restful api gin

· json · rss
#golang 
View url →

About

Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster than martini, it builds up with httprouter.

It is very easy to use just import the repo like "$ go get -u github.com/gin-gonic/gin". The only part you need write is the main func part.

package main

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

func main() {

r := gin.Default()

r.GET("/ping", func(c *gin.Context) {

c.JSON(200, gin.H{

"message": "pong",

})

})

r.Run() // listen and serve on 0.0.0.0:8080

}

So clear and easy. But seems it can't be setup into production environment. How about add some production code? Here is snip

s := &http.Server{

        Addr: ":8080",

        Handler: r,

        ReadTimeout: 15 * time.Second,

        WriteTimeout: 15 * time.Second,

        MaxHeaderBytes: 1 << 20,

    }

    go func() {

        // connect service

        if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {

            log.Fatalf("listen: %s\n", err)

        }

    }()

    // wait the signal to graceful shutdown server(with 5 seconds timeout)

    quit := make(chan os.Signal)

    signal.Notify(quit,

        syscall.SIGHUP, syscall.SIGINT,

        syscall.SIGTERM, syscall.SIGQUIT,

        syscall.SIGUSR1, syscall.SIGUSR2,

        syscall.SIGKILL)

    <-quit

    log.Println("Shutdown server ...")

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

    defer cancel()

    if err := s.Shutdown(ctx); err != nil {

        log.Fatal("Server shutdown error: ", err)

    }

    log.Println("Server exiting.")

That's all, if you concern these code, I will introduce you to take a look at Bilibili backend service that leaked out recently. It has been proved by production.