packagemainimport("fmt""time""github.com/aisk/vox")funcmain(){app:=vox.New()// custom middleware that add a x-response-time to the response headerapp.Use(func(ctx*vox.Context,*vox.Request,res*vox.Response){start:=time.Now()ctx.Next()duration:=time.Now().Sub(start)res.Header.Set("X-Response-Time",fmt.Sprintf("%s",duration))})// router paramapp.Get("/hello/{name}",func(ctx*vox.Context,*vox.Request,res*vox.Response){res.Body="Hello, "+req.Params["name"]+"!"})// responseapp.Get("/",func(ctx*vox.Context,*vox.Request,res*vox.Response){// get the query stringname:=req.URL.Query().Get("name")ifname==""{name="World"}res.Body="Hello, "+name+"!"})app.Run("localhost:3000")}
Handle HTTP Methods
packagemainimport("github.com/aisk/vox")funchandler(ctx*vox.Context,*vox.Request,res*vox.Response){// Get the current request's HTTP method and put it to the result page.res.Body="HTTP Method is: "+req.Method}funcmain(){app:=vox.New()app.Get("/",handler)app.Post("/",handler)app.Put("/",handler)app.Delete("/",handler)app.Head("/",handler)app.Options("/",handler)app.Trace("/",handler)// In some case you need handle custom HTTP method that not in the RFCs like FLY.app.Route("FLY","/",handler)app.Run("localhost:3000")}
packagemainimport("github.com/aisk/vox")functowel(ctx*vox.Context,*vox.Request,res*vox.Response){// Set the response body, it can be string or []byte or any thing that json.Marshal accepts.res.Body="new towel is created!"// Set the response status code.res.Status=201// Set the response header.res.Header.Set("Location","/towels/42")}funcmain(){app:=vox.New()app.Post("/towels",towel)app.Run("localhost:3000")}
Processing JSON request and send JSON response
packagemainimport("encoding/json""net/http""strings""github.com/aisk/vox")typeErrorstruct{Codeint`json:"code"`Messagestring`json:"message"`}typeTowelstruct{Colorstring`json:"color"`Sizestring`json:"size"`}functowel(ctx*vox.Context,*vox.Request,res*vox.Response){if!strings.HasPrefix(req.Header.Get("Content-Type"),"application/json"){res.Status=http.StatusUnsupportedMediaType// or just 415// Set the body with a map, vox will marshal it to JSON automatically for you.res.Body=map[string]interface{}{"code":1,"message":"This is not a JSON request",}return}vartToweliferr:=json.NewDecoder(req.Body).Decode(&t);err!=nil{res.Status=http.StatusUnprocessableEntity// or just 422res.Body=map[string]interface{}{"code":1,}}// Set the body with a struct, vox will marshal it to JSON automatically for you.res.Body=t// Set the response status code.res.Status=201// Set the response header.res.Header.Set("Location","/towels/42")}funcmain(){app:=vox.New()app.Post("/towels",towel)app.Run("localhost:3000")}