Modern microservice web framework of golang

gogo

CircleCI Coverage GoDoc

gogo is an open source, high performance RESTful api framework for the Golang programming language. It also support RPC api, which is similar to gRPC, defined by protobuf.

It's heavily inspired from rails for best practice.

NOTE: From VERSION 2, gogo requires go1.10+ support. We Strongly advice you to start from it for your product. If you want to support go1.6 or older, please use released tag v1.1.0 instead.

Install

$ go get github.com/dolab/gogo/cmd/gogo
  • Create application using scaffold tools
# show gogo helps
$ gogo -h

# create a new application
$ gogo new myapp

# resolve dependences
$ cd myapp
$ make

# generate controller
# NOTE: you should update application.go and add app.Resource("/user", User) route by hand
$ gogo g c user

# generate filter
$ gogo g f session

# generate model
$ gogo g m user

# run test
$ make

# run development server
$ make godev

Getting Started

  • Normal
package main

import (
	"net/http"

	"github.com/dolab/gogo"
)

func main() {
	// load config from config/application.yml
	// app := gogo.New("development", "/path/to/[config/application.yml]")

	// load config from filename
	// app := gogo.New("development", "/path/to/config.yml")

	// use default config
	app := gogo.NewDefaults()

	// GET /
	app.GET("/", func(ctx *gogo.Context) {
		ctx.Text("Hello, gogo!")
	})

	// GET /hello/:name
	app.HandlerFunc(http.MethodGet, "/hello/:name", func(w http.ResponseWriter, r *http.Request) {
		params := gogo.NewParams(r)

		name := params.Get("name")
		if name == "" {
			name = "gogo"
		}

		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Hello, " + name + "!"))
	})

	app.Run()
}
  • Using Middlewares

Middlewares is the best practice of doing common processing when handling a request.

package main

import (
	"github.com/dolab/gogo"
)

func main() {
	app := gogo.NewDefaults()

	// avoid server quit by registering a recovery filter
	app.Use(func(ctx *gogo.Context) {
		if panicErr := recover(); panicErr != nil {
			ctx.Logger.Errorf("[PANICED] %v", panicErr)

			ctx.SetStatus(http.StatusInternalServerError)
			ctx.Json(map[string]interface{}{
				"panic": panicErr,
			})
			return
		}

		ctx.Next()
	})

	// GET /
	app.GET("/", func(ctx *gogo.Context) {
		panic("Oops ~ ~ ~")
	})

	app.Run()
}
  • Using AppGroup

AppGroup is useful when defining resources with shared middlewares and the same uri prefix.

package main

import (
	"encoding/base64"
	"net/http"
	"strings"

	"github.com/dolab/gogo"
)

func main() {
	app := gogo.NewDefaults()

	// avoid server quit by registering recovery func global
	app.Use(func(ctx *gogo.Context) {
		if panicErr := recover(); panicErr != nil {
			ctx.Logger.Errorf("[PANICED] %v", panicErr)

			ctx.SetStatus(http.StatusInternalServerError)
			ctx.Json(map[string]interface{}{
				"panic": panicErr,
			})
			return
		}

		ctx.Next()
	})

	// NewGroup creates sub resources with /v1 prefix, and apply basic auth filter for all sub-resources.
	// NOTE: it combines recovery filter from previous.
	v1 := app.NewGroup("/v1", func(ctx *gogo.Context) {
		auth := ctx.Header("Authorization")
		if !strings.HasPrefix(auth, "Basic ") {
			ctx.SetStatus(http.StatusForbidden)
			return
		}

		b, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(auth, "Basic "))
		if err != nil {
			ctx.Logger.Errorf("Base64 decode error: %v", err)

			ctx.SetStatus(http.StatusForbidden)
			return
		}

		tmp := strings.SplitN(string(b), ":", 2)
		if len(tmp) != 2 || tmp[0] != "gogo" || tmp[1] != "ogog" {
			ctx.SetStatus(http.StatusForbidden)
			return
		}

		// settings which can used by following filters and handler
		ctx.Set("username", tmp[0])

		ctx.Next()
	})

	// GET /v1/user
	v1.GET("/user", func(ctx *gogo.Context) {
		username := ctx.MustGet("username").(string)

		ctx.Text("Hello, " + username + "!")
	})

	app.Run()
}
  • Use Resource Controller

You can implement a controller with optional Index, Create, Explore, Show, Update and Destroy methods, and use app.Resource("/myresource", &MyController) to register all RESTful routes auto.

NOTE: When your resource has a inheritance relationship, there MUST NOT be two same id key. you can overwrite default id key by implementing ControllerID interface.

package main

import (
	"github.com/dolab/gogo"
)

type GroupController struct{}

// GET /group
func (t *GroupController) Index(ctx *gogo.Context) {
	ctx.Text("GET /group")
}

// GET /group/:group
func (t *GroupController) Show(ctx *gogo.Context) {
	ctx.Text("GET /group/" + ctx.Params.Get("group"))
}

type UserController struct{}

// overwrite default :user key with :id
func (t *UserController) ID() string {
	return "id"
}

// GET /group/:group/user/:id
func (t *UserController) Show(ctx *gogo.Context) {
	ctx.Text("GET /group/" + ctx.Params.Get("group") + "/user/" + ctx.Params.Get("id"))
}

func main() {
	app := gogo.NewDefaults()

	// register group controller with default :group key
	group := app.Resource("/group", &GroupController{})

	// nested user controller within group resource
	// NOTE: it overwrites default :user key by implmenting gogo.ControllerID interface.
	group.Resource("/user", &UserController{})

	app.Run()
}

Configures

  • Server
---
name: gogo
mode: test

default_server: &default_server
  addr: localhost
  port: 9090
  ssl: false
  request_timeout: 3
  response_timeout: 10
  request_id: X-Request-Id

default_logger: &default_logger
  output: nil
  level: debug
  filter_params:
    - password
    - password_confirmation

sections:
  test:
    server:
      <<: *default_server
      request_id: ''
    logger:
      <<: *default_logger
    domain: https://example.com
    getting_start:
      greeting: Hello, gogo!
    debug: false

Benchmarks

benchmarks

TODOs

  • server config context
  • support http.Request context
  • scoffold && generator
  • mountable third-part app
  • gRPC support

Thanks

Author

Spring MC

LICENSE

The MIT License (MIT)

Copyright (c) 2016

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Owner
Do framework of golang
null
Similar Resources

Golang Caching Microservice (bequant.io test project to get hired)

bequant test project How to use: Simply type docker-compose up -d --build db warden distributor in terminal while in project's directory. MySQL, Warde

May 14, 2022

Microservice to manager users with golang

User Service Microservice to manager users. Assumptions & Limitations This API a

Dec 27, 2021

Golang Microservice making use of protobuf and gRPC as the underlying transport protocol.

Go-Microservices Golang Microservice making use of protobuf and gRPC as the underlying transport protocol. I will be building a generic microservice,

Jan 5, 2022

Go-rifa-microservice - Clean Architecture template for Golang services

Go-rifa-microservice - Clean Architecture template for Golang services

Test CI Go Clean template Clean Architecture template for Golang services Overvi

Sep 22, 2022

Go gRPC RabbitMQ email microservice

Go, RabbitMQ and gRPC Clean Architecture microservice 👋 👨‍💻 Full list what has been used: GRPC - gRPC RabbitMQ - RabbitMQ sqlx - Extensions to data

Dec 29, 2022

A Microservice Toolkit from The New York Times

A Microservice Toolkit from The New York Times

Gizmo Microservice Toolkit This toolkit provides packages to put together server and pubsub daemons with the following features: Standardized configur

Jan 7, 2023

Go products microservice

Golang Kafka gRPC MongoDB microservice example 👋 👨‍💻 Full list what has been used: Kafka - Kafka library in Go gRPC - gRPC echo - Web framework vip

Dec 28, 2022

Go microservice tutorial project using Domain Driven Design and Hexagonal Architecture!

"ToDo API" Microservice Example Introduction Welcome! 👋 This is an educational repository that includes a microservice written in Go. It is used as t

Jan 4, 2023

A Microservice Toolkit from The New York Times

A Microservice Toolkit from The New York Times

Gizmo Microservice Toolkit This toolkit provides packages to put together server and pubsub daemons with the following features: Standardized configur

May 31, 2021
Comments
  • resource route default mapping

    resource route default mapping

    Now it is:

    // 	article := r.Resource("article")
    // 		GET		/article			Article.Index
    // 		POST	/article			Article.Create
    // 		HEAD	/article/:article	Article.Explore
    // 		GET		/article/:article	Article.Show
    // 		PUT		/article/:article	Article.Update
    // 		DELETE	/article/:article	Article.Destroy
    //
    

    Maybe the better is:

    // 	article := r.Resource("article")
    // 		GET		/article	         Article.Index
    // 		POST	/article	         Article.Create
    // 		HEAD	/article/:id	Article.Explore
    // 		GET		/article/:id	Article.Show
    // 		PUT		/article/:id	Article.Update
    // 		DELETE	/article/:id	Article.Destroy
    //
    
  • ctx.SetStatus not work without ctx.Return()

    ctx.SetStatus not work without ctx.Return()

    eg: when I use ctx.SetStatus(401) to change response's code in Controller without ctx.Return(), the client received response code is 200 rather than 401.

    Why this way, It's so confused.

Microservice - Microservice golang & nodejs
Microservice - Microservice golang & nodejs

Microservice Gabungan service dari bahasa pemograman go, nodejs Demo API ms-auth

May 21, 2022
Customer-microservice - Microservice of customer built with golang and gRPC

?? Building microservices to manage customer data using Go and gRPC Command to g

Sep 8, 2022
Microservice - A sample architecture of a microservice in go

#microservice Folder structure required. service certs config config.yaml loggin

Feb 3, 2022
Kratos is a microservice-oriented governance framework implements by golang
Kratos is a microservice-oriented governance framework implements by golang

Kratos is a microservice-oriented governance framework implements by golang, which offers convenient capabilities to help you quickly build a bulletproof application from scratch.

Dec 27, 2022
Kratos is a microservice-oriented governance framework implements by golang,
Kratos is a microservice-oriented governance framework implements by golang,

Kratos is a microservice-oriented governance framework implements by golang, which offers convenient capabilities to help you quickly build a bulletproof application from scratch.

Dec 31, 2022
Kitex byte-dance internal Golang microservice RPC framework with high performance and strong scalability, customized extensions for byte internal.
Kitex byte-dance internal Golang microservice RPC framework with high performance and strong scalability, customized extensions for byte internal.

Kitex 字节跳动内部的 Golang 微服务 RPC 框架,具有高性能、强可扩展的特点,针对字节内部做了定制扩展。

Jan 9, 2023
a microservice framework for rapid development of micro services in Go with rich eco-system
a microservice framework for rapid development of micro services in Go with rich eco-system

中文版README Go-Chassis is a microservice framework for rapid development of microservices in Go. it focus on helping developer to deliver cloud native a

Dec 27, 2022
Microservice Boilerplate for Golang with gRPC and RESTful API. Multiple database and client supported
Microservice Boilerplate for Golang with gRPC and RESTful API. Multiple database and client supported

Go Microservice Starter A boilerplate for flexible Go microservice. Table of contents Features Installation Todo List Folder Structures Features: Mult

Jul 28, 2022
A microservice gateway developed based on golang.With a variety of plug-ins which can be expanded by itself, plug and play. what's more,it can quickly help enterprises manage API services and improve the stability and security of API services.
A microservice gateway developed based on golang.With a variety of plug-ins which can be expanded by itself, plug and play. what's more,it can quickly help enterprises manage API services and improve the stability and security of API services.

Goku API gateway is a microservice gateway developed based on golang. It can achieve the purposes of high-performance HTTP API forwarding, multi tenant management, API access control, etc. it has a powerful custom plug-in system, which can be expanded by itself, and can quickly help enterprises manage API services and improve the stability and security of API services.

Dec 29, 2022
Trying to build an Ecommerce Microservice in Golang and Will try to make it Cloud Native - Learning Example extending the project of Nic Jackson

Golang Server Project Best Practices Dependency Injection :- In simple words, we want our functions and packages to receive the objects they depend on

Nov 28, 2022