Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork31
A microframework to build web apps; with handler chaining, middleware support, and most of all; standard library compliant HTTP handlers(i.e. http.HandlerFunc).
License
naughtygopher/webgo
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
WebGo is a minimalistic router forGo to build web applications (server side) with no 3rd party dependencies. WebGo will always be Go standard library compliant; with the HTTP handlers having the same signature ashttp.HandlerFunc.
- Router
- Handler chaining
- Middleware
- Error handling
- Helper functions
- HTTPS ready
- Graceful shutdown
- Logging
- Server-Sent Events
- Usage
Webgo has a simplistic, linear path matching router and supports definingURIs with the following patterns
/api/users- URI with no dynamic values/api/users/:userID- URI with a named parameter,
userID - If TrailingSlash is set to true, it will accept the URI ending with a '/', refer tosample
- URI with a named parameter,
/api/users/:misc*- Named URI parameter
misc, with a wildcard suffix '*' - This matches everything after
/api/users. e.g./api/users/a/b/c/d
- Named URI parameter
When there are multiple handlers matching the same URI, only the first occurring handler will handle the request.Refer to thesample to see how routes are configured. You can access named parameters of the URI using theContext function.
Note: webgo Context isnot available inside the special handlers (not found & method not implemented)
funchelloWorld(w http.ResponseWriter,r*http.Request) {// WebGo contextwctx:=webgo.Context(r)// URI paramaters, map[string]stringparams:=wctx.Params()// route, the webgo.Route which is executing this requestroute:=wctx.Routewebgo.R200(w,fmt.Sprintf("Route name: '%s', params: '%s'",route.Name,params,),)}
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, if you setFallThroughPostResponse totrue (refersample).
WebGomiddlware lets you wrap all the routes with a middleware unlike handler chaining. The router exposes a methodUse &&UseOnSpecialHandlers to add a Middleware to the router.
NotFound && NotImplemented are consideredSpecial handlers.webgo.Context(r) within special handlers will returnnil.
Any number of middleware can be added to the router, the order of execution of middleware would beLIFO (Last In First Out). i.e. in case of the following code
funcmain() {router.Use(accesslog.AccessLog,cors.CORS(nil))router.Use(<moremiddleware>)}
CorsWrap would be executed first, followed byAccessLog.
Webgo context has 2 methods toset &get erro within a request context. It enables Webgo to implement a single middleware where you can handle error returned within an HTTP handler.set error,get error.
WebGo provides a few helper functions. When usingSend orSendResponse (other Rxxx responder functions), the response is wrapped in WebGo'sresponse struct and is serialized as JSON.
{"data":"<any valid JSON payload>","status":"<HTTP status code, of type integer>"}When usingSendError, the response is wrapped in WebGo'serror response struct and is serialzied as JSON.
{"errors":"<any valid JSON payload>","status":"<HTTP status code, of type integer>"}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()...)gorouter.StartHTTPS()router.Start()
Graceful shutdown lets you shutdown the server without affecting any live connections/clients connected to the server. Any new connection request after initiating a shutdown would be ignored.
Sample code to show how to use shutdown
funcmain() {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()...)gofunc() {<-osSig// Initiate HTTP server shutdownerr:=router.Shutdown()iferr!=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)// }}()gofunc(){time.Sleep(time.Second*15)signal.Notify(osSig,os.Interrupt,syscall.SIGTERM)}()router.Start()}
WebGo exposes a singleton & global scoped logger variableLOGHANDLER with which you can plug in your custom logger by implementing theLogger interface.
The default logger uses Go standard library'slog.Logger withos.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 theGlobalLoggerConfig(stdout, stderr, cfgs...) function.
MDN has a very good documentation of what SSE (Server-Sent Events) are. The sample app provided shows how to use the SSE extension of webgo.
A fully functional sample is providedhere.
Referhere to find out details about making a contribution
Thanks to all thecontributors
The gopher used here was created usingGopherize.me. WebGo stays out of developers' way, so sitback and enjoy a cup of coffee.
About
A microframework to build web apps; with handler chaining, middleware support, and most of all; standard library compliant HTTP handlers(i.e. http.HandlerFunc).
Topics
Resources
License
Code of conduct
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
