Git Product home page Git Product logo

cotton's Introduction

GoDoc Release Build Status Go Go Report Card

Cotton is a RESTful web framework written by Go (Golang). It's fast and scalable.

Contents

Installation

To install Cotton package, you need to install Go and set your Go workspace first.

  1. The first need Go installed (go 1.13 or later)
  2. install Cotton
go get -u github.com/tonny-zhang/cotton
  1. Import it in your code:
import "github.com/tonny-zhang/cotton

Quick start

You can find more in example/*

package main

import "github.com/tonny-zhang/cotton"

func main() {
	r := cotton.NewRouter()
	r.Get("/hello", func(ctx *cotton.Context) {
		ctx.String("hello world from cotton")
	})

	r.Run(":8080")
}

Feature

API Example

You can find a number of ready-to-run examples at examples project

Using GET, POST, PUT, OPTIONS, DELETE, PATCH, HEAD

func main() {
	r := cotton.NewRouter()
	r.Get("/hello", handler)
	r.Post("/hello", handler)

	r.Run(":8080")
}

Parameters in path

func main() {
	r := cotton.NewRouter()
	// /user/tonny		=> 	match
	// /user/123 		=> 	match
	// /user			=> 	no
	// /user/			=> 	no
	r.Get("/user/:name", func(c *cotton.Context) {
		c.String(200, "hello "+c.Param("name"))
	})

	// /file/test		=> 	match
	// /file/a/b/c		=> 	match
	// /room/			=> 	no
	r.Get("/file/*file", func(c *cotton.Context) {
		c.String(200, "file = "+c.Param("file"))
	})

	r.Run(":8080")
}

Querystring parameters

func main() {
	r := cotton.NewRouter()
	r.Get("/get", func(ctx *cotton.Context) {
		name := ctx.GetQuery("name")
		first := ctx.GetDefaultQuery("first", "first default value")

		ids := ctx.GetQueryArray("ids[]")
		m, _ := ctx.GetQueryMap("info")
		ctx.String(http.StatusOK, fmt.Sprintf("name = %s, first = %s, ids = %v, info = %v", name, first, ids, m))
	})

	r.Run("")
}

Using middleware

func main() {
	r := cotton.NewRouter()

	r.Use(cotton.Recover())
	r.Use(cotton.Logger())

	r.Get("/hello", func(c *cotton.Context) {
		c.String(200, "hello")
	})
	r.Run(":8080")
}

Using group

func main() {
	r := cotton.NewRouter()
	g1 := r.Group("/v1", func(ctx *cotton.Context) {
		// use as a middleware in group
	})
	g1.Use(func(ctx *cotton.Context) {
		fmt.Println("g1 middleware 2")
	})
	{
		g1.Get("/a", func(ctx *cotton.Context) {
			ctx.String(200, http.StatusOK, "g1 a")
		})
	}

	r.Get("/v2/a", func(ctx *cotton.Context) {
		ctx.String(200, http.StatusOK, "hello v2/a")
	})

	r.Run(":8080")
}

Custom NotFound

func main() {
	r := cotton.NewRouter()
	r.NotFound(func(ctx *cotton.Context) {
		ctx.String(http.StatusNotFound, "page ["+ctx.Request.RequestURI+"] not found")
	})

	r.Run(":8080")
}

Custom group NotFound

func main() {
	r := cotton.NewRouter()
	r.NotFound(func(ctx *cotton.Context) {
		ctx.String(http.StatusNotFound, "page ["+ctx.Request.RequestURI+"] not found")
	})
	g1 := r.Group("/v1/", func(ctx *cotton.Context) {
		fmt.Println("g1 middleware")
	})
	g1.NotFound(func(ctx *cotton.Context) {
		ctx.String(http.StatusNotFound, "group page ["+ctx.Request.RequestURI+"] not found")
	})
	r.Run(":8080")
}

Custom static file

func main() {
	dir, _ := os.Getwd()
	r := cotton.NewRouter()

	r.Use(cotton.Logger())
	// use custom static file
	r.Get("/v1/*file", func(ctx *cotton.Context) {
		file := filepath.Join(dir, ctx.Param("file"))

		http.ServeFile(ctx.Response, ctx.Request, file)
	})

	// use router.StaticFile
	r.StaticFile("/s/", dir, true)  // list dir
	r.StaticFile("/m/", dir, false) // 403 on list dir

	g := r.Group("/g/", func(ctx *cotton.Context) {
		fmt.Printf("status = %d param = %s, abspath = %s\n", ctx.Response.GetStatusCode(), ctx.Param("filepath"), filepath.Join(dir, ctx.Param("filepath")))
	})
	g.StaticFile("/", dir, true)

	r.Run("")
}

Use template

use router.LoadTemplates and ctx.Render; go to example/template for detail

PostForm

use method

  • ctx.GetPostForm
  • ctx.GetPostFormArray
  • ctx.GetPostFormMap
  • ctx.GetPostFormFile
  • ctx.GetPostFormArray
  • ctx.SavePostFormFile

go to example/post/ for detail

Benchmarks

the benchmarks code for cotton be found in the cotton-bench repository, so performance of cotton is good!

   cottonRouter:     90888 bytes
 BeegoMuxRouter:    107952 bytes
     BoneRouter:    100712 bytes
      ChiRouter:     75600 bytes
     HttpRouter:     36016 bytes
       trie-mux:    131568 bytes
      GoRouter1:     83112 bytes
goos: darwin
goarch: amd64
pkg: cottonbench
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
BenchmarkHttpRouterWithGithubAPI-8                 38082             31611 ns/op    13856 B/op        169 allocs/op
BenchmarkCottonRouterWithGithubAPI-8               34648             35496 ns/op        0 B/op          0 allocs/op
BenchmarkBeegoMuxRouterWithGithubAPI-8              9888            120716 ns/op   139056 B/op       1050 allocs/op
BenchmarkBoneRouterWithGithubAPI-8                   640           1869374 ns/op   744018 B/op       8893 allocs/op
BenchmarkTrieMuxRouterWithGithubAPI-8              17448             68756 ns/op    66624 B/op        543 allocs/op
BenchmarkGoRouter1WithGithubAPI-8                     60          18084650 ns/op 14432841 B/op     132968 allocs/op

Author

Acknowledgements

This package is inspired by the following

cotton's People

Contributors

tonny-zhang avatar

Stargazers

 avatar

Watchers

 avatar  avatar

cotton's Issues

request uri has multiple /, show 404 not found

Describe the bug
request uri has multiple /, show 404 not found.

now has router /a

http://test.com//a

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

many request same time; and get wrong response

Describe the bug

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/tonny-zhang/cotton"
)

func main() {
	router := cotton.Default()

	router.Get("/a", func(ctx *cotton.Context) {
		fmt.Println("req a1")
		time.Sleep(time.Second * 2)

		ctx.String(http.StatusOK, "router a")
		fmt.Println("req a2")
	})
	router.Get("/b", func(ctx *cotton.Context) {
		fmt.Println("req b1")
		time.Sleep(time.Second * 3)
		ctx.String(http.StatusOK, "router b")
		fmt.Println("req b1")
	})
	router.Run("")
}

To Reproduce
Steps to reproduce the behavior:

  1. curl http://localhost:5000/a => empty response
  2. curl http://localhost:5000/b => router arouter b or router b or router a

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.