Giter Club home page Giter Club logo

strv-backend-go-net's Introduction

STRV net

Latest release codecov GitHub

Go package facilitating writing API applications in a fast and easy manner.

Available packages

errors

Definition of common errors.

net

Common functionality that comes in handy regardless of the used API architecture. net currently supports generating request IDs with some helper methods.

http

Wrapper around the Go native http server. http defines the Server that can be configured by the ServerConfig. Implemented features:

  • Started http server can be easily stopped by cancelling the context that is passed by the Run method.
  • The Server can be configured with a slog.Logger for logging important information during starting/ending of the server.
  • The Server listens for SIGINT and SIGTERM signals so it can be stopped by firing the signal.
  • By the ServerConfig can be configured functions to be called before the Server ends.

http defines several helper consctructs:

  • Content types and headers which are frequently used by APIs.
  • Middlewares:
    • RequestIDMiddleware sets request id in to the context.
    • RecoverMiddleware recovers from panic and sets panic object into the response writer for logging.
    • LoggingMiddleware logs information about the request (method, path, status code, request id, duration of the request, error message and panic message).
  • Method WriteResponse for writing a http response and WriteErrorResponse for writing an error http response. Writing of responses can be configured by ResponseOption.

Examples

http

Starting the server:

package main

import (
	...

	httpx "go.strv.io/net/http"
)

func main() {
	...
	h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
		Level: level,
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey {
				a.Value = slog.StringValue(a.Value.Time().Format("2006-01-02T15:04:05.000Z"))
			}
			return a
		},
	})
	l := slog.New(h)
	serverConfig := httpx.ServerConfig{
		Addr:    ":8080",
		Handler: handler(), // define your http handler
		Hooks: httpx.ServerHooks{
			BeforeShutdown: []httpx.ServerHookFunc{
				func(_ context.Context) {
					storage.Close() // it may be useful for example to close a storage before the server ends
				},
			},
		},
		Limits: nil,
		Logger: l.WithGroup("httpx.Server"), // the server expects *slog.Logger
	}
	server := httpx.NewServer(&serverConfig)
	if err = server.Start(ctx); err != nil {
		l.Error("HTTP server unexpectedly ended", slog.Any("error", err))
	}
}

Writing http responses:

func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
	userID := userIDFromCtx(r.Context())
	
	user, err := h.service.GetUser(r.Context(), userID)
	if err != nil {
		_ = httpx.WriteErrorResponse(w, http.StatusInternalServerError, httpx.WithErrorCode("ERR_UNKNOWN"))
		return
	}
	
	userResp := model.ToUser(user)
	_ = httpx.WriteResponse(w, userResp, http.StatusOK)
}

strv-backend-go-net's People

Contributors

tomaskocman avatar cermakm avatar fazt01 avatar viking3s avatar xburda4 avatar

Stargazers

 avatar Petr Chalupa avatar  avatar  avatar Matúš Bafrnec avatar  avatar

Watchers

Pavel Poláček avatar Martin Stava avatar Honza Hovorka avatar Jiri Koutny avatar Dyego Rodrigo avatar Daniel Kraus avatar Otávio Augusto avatar  avatar Desmond avatar  avatar Lev Andreev avatar Matej Sojak avatar  avatar  avatar  avatar

strv-backend-go-net's Issues

Logging middleware should allow custom

Inspiration what to put in the description:

I would like to extend the data logged by the logging middleware by custom data. Currently, that's not completely possible. While I can pass custom logging fields to the logger accepted as an input to the middleware, if the data I need comes from other middleware (evaluated from the contextual headers at runtime), then I have no way of injecting them to the logging middelware.

Benefits of the feature

While we can add ad hoc fields to the RequestData, implementing it in a generic way would be more flexible.

Checklist

  • I have read the CONTRIBUTING.md.
  • I have checked if I'm using the latest version and if I can get the desired behavior by changing the configuration. You might discover that the feature is already available.
  • I have searched the existing issues and discussions to see if the feature has already been suggested.

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.