Skip to content

mxrcury/rootgo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Root

Simple and lightweight HTTP router/server for Golang

⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣷⠀⠀⠀⢀⣤⣾⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⣀⣀⣀⠀⠀⠀⠹⣧⡀⠀⣿⣿⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠈⠻⣿⣿⣷⣦⣄⠘⣷⡀⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⠛⠛⠛⠀⠘⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣹⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⡿⠀⢴⣾⠿⠛⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⢲⣶⣶⣶⡖⠒⠒⠒⠒⠒⠒⠒⠒⠒⠒⠀⠀
⠀⠀⠀⠀⠀⢠⡶⠾⠆⠀⠀⠀⠀⣸⣿⠁⠈⠙⢷⡶⠶⣦⣄⡀⠀⠀⠀⠀⠀⠀
⠀⠸⠷⣦⡀⠘⢷⣄⠀⠀⠀⠀⢠⡿⣯⡀⠀⠀⠈⢿⡄⠀⠉⠁⠀⠀⣠⡄⠀⠀
⠀⠀⢠⡾⠿⠛⠻⠿⠿⠶⠶⠾⠛⢁⣸⣷⣦⣀⠀⠈⠁⠀⠀⢀⣤⣾⡋⠀⠀⠀
⠀⠀⣿⠁⠀⠀⠀⠀⠀⠀⠀⢀⣴⠿⣯⣀⡀⠉⠙⠛⠓⠒⠚⠋⠁⠈⢿⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠀⠀⠀

Current features overview

  • Adding GET, POST, PATCH, PUT, DELETE endpoints
  • Routes with params
  • Getting value of params, several params with the same name presented as slice
  • Router can be used both with standard library and our server wrapper
  • Server wrapper that implements some high level utils(Write, WriteFiles)
  • Working with views

Coming features

  • [Server] Implement caching(in memory and in redis or any other db that implement Cache interface in /caching/cache.go)

Usage example

func main(){
	r := router.NewRouter("/api")

	server := api.NewServer(r, api.Options{Port: "8000"})

	server.ASSETS("/assets")

	server.GET("/users/contacts/:id", func(ctx *api.Context) {
		ids := ctx.Params.Get("id")
		ctx.WriteJSON("GET id:"+id[0], 200)
	})

	server.POST("/users", func(ctx *api.Context) {
		user := new(User)
		err := ctx.Body.Decode(user)

		if err != nil {
			ctx.WriteError(types.Error{Message: "You entered wrong values", Status: 400})
		}

		if err := ctx.Write(user, 200); err != nil {
			ctx.WriteError(types.Error{Message: "Internal server error", Status: 500})
		}
	})

	server.GET("/document", func(ctx *api.Context) {
		file, err := os.ReadFile("./assets/doc.pdf")
		if err != nil {
			ctx.WriteError(types.Error{Message: err.Error(), Status: 500})
		}

		ctx.WriteFile(200, file, api.PDFFileType)
	})

	server.Run()
}

Usage only router without server wrapper

func main(){
	r := router.NewRouter("/api")

	r.GET("/users/:id", func(ctx *router.Context, w http.ResponseWriter, r *http.Request) {
		ids := ctx.Params.Get("id")
		io.WriteString(w, "Your user's ID is:"+ids[0])
	})

	r.POST("/users", func(ctx *router.Context, w http.ResponseWriter, r *http.Request) {
		user := new(User)
		err := ctx.Body.Decode(user)

		if err != nil {
			util.WriteError(w, types.Error{Message: "Wrong creation", Status: 400})
		}

		io.WriteString(w, "user was successfully created")
	})

	log.Fatalln(http.ListenAndServe(":"+cfg.Http.Port, r))
	

Licensed by MIT

About

HTTP router/server for Golang

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages