A minimal framework to build web apps; with handler chaining, middleware support; and most of all standard library compliant HTTP handlers(i.e. http.HandlerFunc).

webgo gopher

coverage

WebGo v4.1.3

WebGo is a minimalistic framework for Go to build web applications (server side) with zero 3rd party dependencies. Unlike full-fledged frameworks, it gets out of your way as soon as possible in the execution flow. WebGo has always been and will always be Go standard library compliant; with the HTTP handlers having the same signature as http.HandlerFunc.

Important

  • Regression introduced in v4.0.4, exists on v4.0.6 as well. Requests panic when not using Webgo's response methods (e.g. R200, Send, SendResponse etc.) because the default HTTP status is set as 0

  • ContextPayload.URIParams(*http.Request)map[string]string was replaced despite being newly introduced in v3.5.4. The new function is ContextPayload.Params()map[string]string, and has a slight performance advantage compared to URIParams

Index

  1. Router
  2. Handler chaining
  3. Middleware
  4. Helper functions
  5. HTTPS ready
  6. Graceful shutdown
  7. Logging
  8. Usage

Router

The router is one of the most important component of a web application. It helps identify the HTTP requests and pass them on to respective handlers. A handler is identified using a URI. WebGo supports defining URIs with the following patterns

  1. /api/users
    • Static URI pattern with no variables
  2. /api/users/:userID
    • URI pattern with variable userID (named URI parameter)
    • This will not match /api/users/johndoe/account. It only matches till /api/users/johndoe/
      • If TrailingSlash is set to true, refer to sample
  3. /api/users/:misc*
    • Named URI variable misc
    • This matches everything after /api/users. e.g. /api/users/a/b/c/d

If multiple patterns match the same URI, the first matching handler would be executed. Refer to the sample to see how routes are configured. A WebGo Route is defined as following:

webgo.Route{
	// A name for the API (preferrably unique)
	Name string
	// HTTP verb, i.e. GET, POST, PUT, PATCH, HEAD, DELETE
	Method string
	// The URI pattern
	Pattern string
	// If the URI ends with a '/', should it be considered valid or not? e.g. '/api/users' vs '/api/users/'
	TrailingSlash bool
	// In case of chained handlers, should the execution continue after one of the handlers have 
	// responded to the HTTP request
	FallThroughPostResponse bool
	// The list of HTTP handlers
	Handlers []http.HandlerFunc
}

You can access named parameters of the URI using the Context function.

func helloWorld(w http.ResponseWriter, r *http.Request) {
	// WebGo context
	wctx := webgo.Context(r)
	// URI paramaters, map[string]string
	params := wctx.Params()
	// route, the webgo.Route which is executing this request
	route := wctx.Route
	webgo.R200(
		w,
		fmt.Sprintf(
			"Route name: '%s', params: '%s'", 
			route.Name,
			params, 
			),
	)
}

Handler chaining

Handler chaining lets you execute multiple handlers for a given route. Execution of a chain can be configured to run even after a handler has written a response to the http request. This is made possible by setting FallThroughPostResponse to true (refer sample).

webgo.Route{
	Name: "chained",
	Method: http.MethodGet,
	Pattern: "/api",
	TrailingSlash: false,
	FallThroughPostResponse: true,
	Handlers []http.HandlerFunc{
		handler1,
		handler2,
		.
		.
		.
	}
}

Middleware

WebGo middleware lets you wrap all the routes with a middleware. Unlike handler chaining, middleware applies to all the handlers. All middleware should be of type Middlware. The router exposes a method Use && UseOnSpecialHandlers to add a Middleware to the router. Following code shows how a middleware can be used in WebGo.

import (
	"github.com/bnkamalesh/webgo/v4"
	"github.com/bnkamalesh/webgo/v4/middleware"
)

func routes() []*webgo.Route {
	return []*webgo.Route{
		&webo.Route{
			Name: "home",
			Method: http.http.MethodGet,
			Pattern: "/",
			Handlers: []http.HandlerFunc{
				func(w http.ResponseWriter, r *http.Request) {
					webgo.R200(w, "home")
				}
			},
		},
	}
}

func main() {
	router := webgo.NewRouter(*webgo.Config{
		Host:         "",
		Port:         "8080",
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 60 * time.Second,
	}, routes())

	router.UseOnSpecialHandlers(middleware.AccessLog)
	
	router.Use(middleware.AccessLog)

	router.Start()
}

Any number of middleware can be added to the router, the order of execution of middleware would be LIFO (Last In First Out). i.e. in case of the following code

func main() {
	router.Use(middleware.AccessLog)
	router.Use(middleware.CorsWrap())
}

CorsWrap would be executed first, followed by AccessLog.

Helper functions

WebGo provides a few helper functions.

  1. ResponseStatus(w http.ResponseWriter) get the HTTP status code from response writer
  2. SendHeader(w http.ResponseWriter, rCode int) - Send only an HTTP response header with the provided response code.
  3. Send(w http.ResponseWriter, contentType string, data interface{}, rCode int) - Send any response as is, with the provided content type and response code
  4. SendResponse(w http.ResponseWriter, data interface{}, rCode int) - Send a JSON response wrapped in WebGo's default response struct.
  5. SendError(w http.ResponseWriter, data interface{}, rCode int) - Send a JSON response wrapped in WebGo's default error response struct
  6. Render(w http.ResponseWriter, data interface{}, rCode int, tpl *template.Template) - Render renders a Go template, with the provided data & response code.

Few more helper functions are available, you can check them here.

When using Send or SendResponse, the response is wrapped in WebGo's response struct and is serialized as JSON.

{
	"data": "<any valid JSON payload>",
	"status": "<HTTP status code, of type integer>"
}

When using SendError, the response is wrapped in WebGo's error response struct and is serialzied as JSON.

{
	"errors": "<any valid JSON payload>",
	"status": "<HTTP status code, of type integer>"
}

HTTPS ready

HTTPS server can be started easily, by providing the key & cert file. You can also have both HTTP & HTTPS servers running side by side.

Start HTTPS server

cfg := &webgo.Config{
	Port: "80",
	HTTPSPort: "443",
	CertFile: "/path/to/certfile",
	KeyFile: "/path/to/keyfile",
}
router := webgo.NewRouter(cfg, routes())
router.StartHTTPS()

Starting both HTTP & HTTPS server

cfg := &webgo.Config{
	Port: "80",
	HTTPSPort: "443",
	CertFile: "/path/to/certfile",
	KeyFile: "/path/to/keyfile",
}

router := webgo.NewRouter(cfg, routes())
go router.StartHTTPS()
router.Start()

Graceful shutdown

Graceful shutdown lets you shutdown the server without affecting any live connections/clients connected to the server. It will complete executing all the active/live requests before shutting down.

Sample code to show how to use shutdown

func main() {
	osSig := make(chan os.Signal, 5)

	cfg := &webgo.Config{
		Host:            "",
		Port:            "8080",
		ReadTimeout:     15 * time.Second,
		WriteTimeout:    60 * time.Second,
		ShutdownTimeout: 15 * time.Second,
	}
	router := webgo.NewRouter(cfg, routes())

	go func() {
		<-osSig
		// Initiate HTTP server shutdown
		err := router.Shutdown()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		} else {
			fmt.Println("shutdown complete")
			os.Exit(0)
		}

		// If you have HTTPS server running, you can use the following code
		// err := router.ShutdownHTTPS()
		// if err != nil {
		// 	fmt.Println(err)
		// 	os.Exit(1)
		// } else {
		// 	fmt.Println("shutdown complete")
		// 	os.Exit(0)
		// }
	}()

	signal.Notify(osSig, os.Interrupt, syscall.SIGTERM)

	router.Start()

	for {
		// Prevent main thread from exiting, and wait for shutdown to complete
		time.Sleep(time.Second * 1)
	}
}

Logging

WebGo exposes a singleton & global scoped logger variable LOGHANDLER with which you can plugin your custom logger. Any custom logger should implement WebGo's Logger interface.

type Logger interface {
    Debug(data ...interface{})
    Info(data ...interface{})
    Warn(data ...interface{})
    Error(data ...interface{})
    Fatal(data ...interface{})
}

Configuring the default Logger

The default logger uses Go standard library's log.Logger with os.Stdout (for debug and info logs) & os.Stderr (for warning, error, fatal) as default io.Writers. You can set the io.Writer as well as disable specific types of logs using the GlobalLoggerConfig(stdout, stderr, cfgs...) function.

GlobalLoggerConfig(nil, nil, LogCfgDisableDebug, LogCfgDisableInfo...)

Usage is shown in cmd/main.go.

Usage

A fully functional sample is provided here. You can try the following API calls with the sample app.

  1. http://localhost:8080/
    • Route with no named parameters configured
  2. http://localhost:8080/matchall/
  3. `http://localhost:8080/api/

How to run the sample

If you have Go installed on your system, open your terminal and:

$ cd $GOPATH/src
$ mkdir -p github.com/bnkamalesh
$ cd github.com/bnkamalesh
$ git clone https://github.com/bnkamalesh/webgo.git
$ cd webgo
$ go run cmd/main.go

Info 2020/06/03 12:55:26 HTTP server, listening on :8080

Or if you have Docker, open your terminal and:

$ git clone https://github.com/bnkamalesh/webgo.git
$ cd webgo
$ docker run \
-p 8080:8080 \
-v ${PWD}:/go/src/github.com/bnkamalesh/webgo/ \
-w /go/src/github.com/bnkamalesh/webgo/cmd \
--rm -ti golang:latest go run main.go

Info 2020/06/03 12:55:26 HTTP server, listening on :8080

Contributing

Refer here to find out details about making a contribution

Credits

Thanks to all the contributors

The gopher

The gopher used here was created using Gopherize.me. WebGo stays out of developers' way, so sitback and enjoy a cup of coffee like this gopher.

Owner
Kamaleshwar
Let's fix this planet, one line of code at a time.
Kamaleshwar
Comments
  • feat: HTTP cache implementation.

    feat: HTTP cache implementation.

    Is your feature request related to a problem? Please describe. An HTTP cache system would be great in webgo to avoid the execution of unchanged response.

    Describe the solution you'd like I can implement Souin as the HTTP cache middleware. With that it will support the CDN validation/invalidation too, set default cache-control header, store in a distributed system using olric or in memory with badger.

    Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

    Additional context It's already available as Træfik/Tyk plugin, skipper/gin/echo middleware, and is used in the official caddy cache-handler.

    Cheers ✌️

  • #7 fixed bug of HTTP response status code

    #7 fixed bug of HTTP response status code

    Thank you for your feedback! Considering the content of the feedback, i fixed again, so please review. I modified to send status code at the timing to execute Write method.

  • Context handling type name is confusing

    Context handling type name is confusing

    Hi

    https://godoc.org/github.com/bnkamalesh/webgo#WC name is confusing. For that reason, comment on the type documents only the meaning of WC shortcut. Please consider renaming it for the next major release

  • Invalid response HTTP status

    Invalid response HTTP status

    file: responses.go

    When responses are send using SendResponse or SendError, in case of a JSON encoding error within these functions, the following happens:

    w.WriteHeader(rCode) // Write header is already called here, this cannot be overwritten if err := json.NewEncoder(w).Encode(&dOutput{data, rCode}); err != nil { Log.Println(err) R500(w, ErrInternalServer) // HTTP response status set by this function will not work }

    So the response in such cases would look like this: HTTP Status: 200 { errors: "Internal server error occurred", status: 500 }

  • [major] NewRouter function now accepts optional Routes instead of sli…

    [major] NewRouter function now accepts optional Routes instead of sli…

    …ce of Routes

    [minor] Router now has a convenience method Add(routes...*Route) [minor] Route grouping feature added (usage available in the sample app, cmd/main.go) [-] updated tests

  • Route example in readme gives error: errors.go:54: Unsupported HTTP request method provided.

    Route example in readme gives error: errors.go:54: Unsupported HTTP request method provided.

    Hello. This code in the readme:

    import (
    	"github.com/bnkamalesh/webgo"
    	"github.com/bnkamalesh/webgo/middleware"
    )
    
    func routes() []*webgo.Route {
    	return []*webgo.Route{
    		&webo.Route{
    			Name: "home",
    			Pattern: "/",
    			Handlers: []http.HandlerFunc{
    				func(w http.ResponseWriter, r *http.Request) {
    					webgo.R200(w, "home")
    				}
    			},
    		},
    	}
    }
    
    func main() {
    	router := webgo.NewRouter(*webgo.Config, routes())
    
    	router.UseOnSpecialHandlers(middleware.AccessLog)
    	
    	router.Use(middleware.AccessLog)
    
    	router.Start()
    }
    

    Doesn't work. You need to define a Method field in the Route struct. Also it complains about *webgo.Config not being an expression (unless it was intentional as a placeholder for any pointer to Config). This works:

    func routes() []*webgo.Route {
    	return []*webgo.Route{
    		&webo.Route{
    			Name: "home",
    			Method: "GET",	
    			Pattern: "/",
    			Handlers: []http.HandlerFunc{
    				func(w http.ResponseWriter, r *http.Request) {
    					webgo.R200(w, "home")
    				}
    			},
    		},
    	}
    }
    
    func main() {
    	config := webgo.Config{
    		Host: "localhost",
    		Port: "8888",
    	}
    	router := webgo.NewRouter(&config, routes())
    
    	router.UseOnSpecialHandlers(middleware.AccessLog)
    	
    	router.Use(middleware.AccessLog)
    
    	router.Start()
    }
    
  • CORS middleware update

    CORS middleware update

    CORS middleware provided with the package currently responds with a wildcard *. It should be updated to accept a list of domains, and default to wildcard if no domains provided.

    • [x] All CORS middleware functions should accept an optional list of domains
    • [ ] Do not break backward compatibility / New functions if cannot maitnain backward compatibility
  • fixed readme and type

    fixed readme and type

    I fixed REAMD.md and typo.

    By the following modification, it becomes 15ns when Timeout: 15 was set. 4351cfa6e17120f16dae4f5e2b5fc63186461cda

    Duration: https://golang.org/pkg/time/#Duration

  • #7 fixed bug of HTTP response status code

    #7 fixed bug of HTTP response status code

    I fixed bug of issues#7. I changed from Encode function to Marshal. Because Encode function writes the JSON encoding of argument to the stream, but Marshal does JSON encoding only. Therefore, if encoding fails, errors can be picked up.

    Encode: https://golang.org/pkg/encoding/json/#Encoder.Encode Marshal: https://golang.org/pkg/encoding/json/#Marshal

  • Support to choose the logging interface

    Support to choose the logging interface

    By default the logs are printed to stdout. Though, there should be a provision of providing an output of users' choice. Need to update the logging mechanism to use an interface, so that it can be set to a thirdparty/external logger

    • [x] Convert current logs to use an interface
    • [ ] Expose a method to replace the logging interface on the fly (should be concurrency safe)
  • spelling error

    spelling error

    Hello,

    Thanks for developing this simple framework. As a non-voice developer I can easily lift up with your framework. file word written as fil in errors.go file.

    //C003 Error Code 3 C003 = "App environment provided in config fil Accepted values are production or development"

    -Vasu

  • Convenience methods for adding routes

    Convenience methods for adding routes

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

    Adding routes currently requires the developer to prepare a single list of *Route with all the routes defined in one go. This can be split up and made easier for the developer

    Describe the solution you'd like

    We can add convenience method for each type of HTTP method supported by webgo (). e.g.

    router.Add(*Route)
    router.Get("URI",[]Handlers{}, opts...)
    router.Head("URI",[]Handlers{}, opts...)
    router.Post("URI",[]Handlers{}, opts...)
    router.Put("URI",[]Handlers{}, opts...)
    router.Patch("URI",[]Handlers{}, opts...)
    router.Delete("URI",[]Handlers{}, opts...)
    router.Option("URI",[]Handlers{},opts...)
    

    Each method should keep updating routes of the router, for the respective HTTP method.

    Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

    Additional context Add any other context or screenshots about the feature request here.

  • Login Auth solutions.

    Login Auth solutions.

    Is your feature request related to a problem? Please describe. I wanted to get some examples of how to add login authentication. I have some ideas myself, but curious what the world has in mind.

    Describe the solution you'd like I would like to see examples for: Firebase auth 3rd party Auth perhaps some JWT and or cookie solutions

  • Auto HTTPS with Letsencrypt

    Auto HTTPS with Letsencrypt

    If autoTLS is enabled, it should do the following:

    • [ ] Check if there's a certificate path provided, if not, default to a path
    • [ ] Inject acme routes for Letsencrypt verification
    • [ ] Accept list of domains to provide HTTPS
    • [ ] Check expiry of all generated Letsencrypt certificates
    • [ ] Update certificates automatically N days prior to expiry
Gin middleware/handler to enable CORS support.

wcors Gin middleware/handler to enable CORS support. Usage Start using it Download and install it: go get github.com/wyy-go/wcors Import it in your co

Jan 8, 2022
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Jan 5, 2023
This library provides a simple framework of microservice, which includes a configurator, a logger, metrics, and of course the handler

Microservice The framework for the creation of microservices, written in Golang. (note: http microservice) Architecture microservice includes: handle

Dec 30, 2022
Go-app is a package to build progressive web apps with Go programming language and WebAssembly.
Go-app is a package to build progressive web apps with Go programming language and WebAssembly.

Go-app is a package to build progressive web apps with Go programming language and WebAssembly.

Dec 30, 2022
Timeout handler for http request in Gin framework

Middleware to Handle Request Timeout in Gin Installation Installation go get github.com/s-wijaya/gin-timeout Import it in your code: import ( // o

Dec 14, 2021
🚀‏‏‎ ‎‏‏‎‏‏‎‎‎‎‎‎Copper is a Go toolkit complete with everything you need to build web apps.

Copper Copper is a Go toolkit complete with everything you need to build web apps. It focuses on developer productivity and makes building web apps in

Jan 7, 2023
Muxie is a modern, fast and light HTTP multiplexer for Go. Fully compatible with the http.Handler interface. Written for everyone.
Muxie is a modern, fast and light HTTP multiplexer for Go. Fully compatible with the http.Handler interface. Written for everyone.

Muxie ?? ?? ?? ?? ?? ?? Fast trie implementation designed from scratch specifically for HTTP A small and light router for creating sturdy backend Go a

Dec 8, 2022
Web framework for creating apps using Go in Google AppEngine

Welcome to app.go v3.0 app.go is a simple web framework for use in Google AppEngine. Just copy the app folder to your working folder and import it fro

Mar 21, 2021
Goa is a web framework based on middleware, like koa.js.

Goa Goa is under construction, if you are familiar with koa or go and interested in this project, please join us. What is goa? goa = go + koa Just lik

Sep 27, 2022
Golanger Web Framework is a lightweight framework for writing web applications in Go.

/* Copyright 2013 Golanger.com. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except

Nov 14, 2022
The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework.

jin About The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework. If thi

Jul 14, 2022
hiboot is a high performance web and cli application framework with dependency injection support

Hiboot - web/cli application framework About Hiboot is a cloud native web and cli application framework written in Go. Hiboot is not trying to reinven

Nov 20, 2022
based on go lang build WEB development framework for go lang beginners .

based on go lang build WEB development framework for go lang beginners .

Oct 31, 2021
Bootstrapper and middleware for Echo framework in golang.
Bootstrapper and middleware for Echo framework in golang.

rk-echo Interceptor & bootstrapper designed for echo framework. Currently, supports bellow functionalities. Name Description Start with YAML Start ser

Jul 9, 2022
A framework for apps written entirely in YAML, powered by ytt.

yapp A framework for apps written entirely in YAML, powered by ytt. Highly experimental! Do not use! # start the server... go run . -f examples/hello-

May 6, 2022
Roche is a Code Generator and Web Framework, makes web development super concise with Go, CleanArch
Roche is a Code Generator and Web Framework, makes web development super concise with Go, CleanArch

It is still under development, so please do not use it. We plan to release v.1.0.0 in the summer. roche is a web framework optimized for microservice

Sep 19, 2022
A powerful go web framework for highly scalable and resource efficient web application

webfr A powerful go web framework for highly scalable and resource efficient web application Installation: go get -u github.com/krishpranav/webfr Exa

Nov 28, 2021
A powerful go web framework for highly scalable and resource efficient web application

A powerful go web framework for highly scalable and resource efficient web application

Oct 3, 2022