Git Product home page Git Product logo

adk's Introduction

ADK - Golang API Development Kit

CircleCI Go Report GolangCI License

GoDoc Reference:

  • api:
  • errors:
  • respond:

GOPHERCON 2022 | ADK - Golang API Development Kit


Common utilities to write simple apis in golang.

- Custom API Handlers
  - Custom API Request(JSON) Decoders
  - Custom API URL Query-params Decoders using gorrila schema.
- App Errors
- Response Writers

Ex: Conventional way of writing api

package main

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Post("/user", CreateUserHandler)
	http.ListenAndServe(":3000", r)
}

// CreateUserHandler creates a new users
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()

	reqBts, err := ioutil.ReadAll(r.Body)
	if err != nil {
        w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
        w.Write([]byte(`{"error": "Couldn't read request body"}`))
		return
	}

	var createReq createUserReq
	jErr := json.Unmarshal(reqBts, &createReq)
	if jErr != nil {
        w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
        w.Write([]byte(`{"error": "invalid request body"}`))
		return
	}
    if err := validateCreateUserReq(&createReq); err != nil {
        w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
        w.Write([]byte(`{"error": "invalid request body"}`))
		return
    }
    if err := store.CreateUser(&createReq); err != nil {
        w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte(`{"error": "invalid request body"}`))
		return
    }

    // respond to the client
    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write([]byte(`{"message": "user created successfully", "id": 123}`))
}

After using custom handlers and ADK

package main

import (
	"net/http"

    "github.com/manigandand/adk/api"
    "github.com/manigandand/adk/errors"
    "github.com/manigandand/adk/middleware"
    "github.com/manigandand/adk/respond"

	"github.com/go-chi/chi/v5"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)

	r.Method(http.MethodPost, "/user", api.Handler(CreateUserHandler))
	http.ListenAndServe(":3000", r)
}

type createUserReq struct {
    Email string `json:"email"`
    Name  string `json:"name"`
}

func (c *createUserReq) Validate() *errors.AppError {
    if c.Email == "" {
        return errors.KeyRequired("email")
    }
    return nil
}

// CreateUserHandler creates a new users
func CreateUserHandler(w http.ResponseWriter, r *http.Request) *errors.AppError{
    ctx := r.Context()

	var createReq createUserReq

	if err := api.Decode(r, &createReq); err != nil {
		return err
	}
    if err := store.CreateUser(&createReq); err != nil {
		return err
    }

    // respond to the client
    return respond.OK(w, map[string]interface{}{
        "message": "user created successfully",
        "id": 123,
    })
}

NOTE: Decoder currently will work on only on the "application/json" body.

adk's People

Contributors

manigandand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

adk's Issues

Support List Errors

Is your feature request related to a problem? Please describe.
Handle multiple errors at once when processing the a/sync process.

Describe the solution you'd like
Support for storing and handling multiple errors.

Describe alternatives you've considered

Additional context

type lIstErrors []*AppErrors

Goroutine pool model

Is your feature request related to a problem? Please describe.
Goroutine pool package

Describe the solution you'd like
Goroutine pool package

Describe alternatives you've considered

Additional context

type pool struct {
    size int
    ch chan struct{} // buffered channel
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.