Quick Start
Installation
To install Slim, Go 1.21.0 or higher is required.
$ mkdir myapp && cd myapp
$ go mod init myapp
$ go get go-slim.dev/slim
Instance
Any object of type slim.Slim can be considered a Slim instance, and we can use any number of Slim instances in a single program.
s := slim.New()
Using the function slim.New only initializes a basic Slim instance without registering any middleware.
Hello world!
Create the entry file server.go
package main
import (
"net/http"
"log"
"go-slim.dev/slim"
)
func main() {
s := slim.New()
s.GET("/", func(c slim.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
log.Fatal(s.Start(":1324"))
}
Start the server
$ go run server.go
Open the URL http://localhost:1324, and we can see the string Hello, World! on the page.
Routing
s.POST("/users", saveUser)
s.GET("/users/:id", getUser)
s.PUT("/users/:id", updateUser)
s.DELETE("/users/:id", deleteUser)
Path Parameters
// s.GET("/users/:id", getUser)
func getUser(c slim.Context) error {
// User ID from path `users/:id`
id := c.PathParam("id")
return c.String(http.StatusOK, id)
}
Open the URL http://localhost:1324/users/joe, and we'll see the string joe on the page.
Query Parameters
// s.GET("/show", show)
func show(c slim.Context) error {
// Get team and member from the query string
team := c.QueryParam("team")
member := c.QueryParam("member")
return c.String(http.StatusOK, "team:" + team + ", member:" + member)
}
Open the URL http://localhost:1324/show?team=x-men&member=wolverine, and we'll see the string team: x-men, member: wolverine on the page.
Form Data
We submit the following data using a form:
| name | value |
|---|---|
| name | Joe Smith |
| joe@go-slim.dev |
// s.POST("/save", save)
func save(c slim.Context) error {
// Get name and email
name := c.FormValue("name")
email := c.FormValue("email")
return c.String(http.StatusOK, "name:" + name + ", email:" + email)
}
We open the console and use the curl command to execute the following command to simulate a form request:
$ curl -d "name=Joe Smith" -d "email=joe@go-slim.dev" http://localhost:1324/save
// => name:Joe Smith, email:joe@go-slim.dev
File Upload
We submit the following data using a form:
| name | value |
|---|---|
| name | Joe Smith |
| avatar | an avatar file |
// s.POST("/save", save)
func save(c slim.Context) error {
// Get name
name := c.FormValue("name")
// Get avatar
avatar, err := c.FormFile("avatar")
if err != nil {
return err
}
// Source
src, err := avatar.Open()
if err != nil {
return err
}
defer src.Close()
// Destination
dst, err := os.Create(avatar.Filename)
if err != nil {
return err
}
defer dst.Close()
// Copy
_, err = io.Copy(dst, src)
if err != nil {
return err
}
return c.HTML(http.StatusOK, "<b>Thank you! " + name + "</b>")
}
Similarly, we use the curl command to execute the following command in the console to simulate a file upload request:
$ curl -F "name=Joe Smith" -F "avatar=@/path/to/your/avatar.png" http://localhost:1324/save
// => <b>Thank you! Joe Smith</b>
To check the uploaded image, run the following command:
$ cd <project directory>
$ ls avatar.png
// => avatar.png
Handling Requests
- Call the method
Context#Bind, and Slim will bind submittedjson,xml,form,query,header, and other data to Go structs based on the value of the request headerContent-Type. - Respond with HTTP status code and render
json,xml, or other formats of data.
type User struct {
Name string `json:"name" xml:"name" form:"name" query:"name"`
Email string `json:"email" xml:"email" form:"email" query:"email"`
}
e.POST("/users", func(c slim.Context) error {
u := new(User)
if err := c.Bind(u); err != nil {
return err
}
return c.JSON(http.StatusCreated, u)
// Or
// return c.XML(http.StatusCreated, u)
})
Static Content
Serve static files for the path /static/.
s.Static("/static", "static")
Template Rendering
The template rendering interface needs to be implemented in advance.
Middleware
package main
import (
"go-slim.dev/slim"
"go-slim.dev/slim/middleware"
)
func main() {
s := slim.New()
// Root level middleware
s.Use(middleware.Logger())
s.Use(middleware.Recovery())
// Group level middleware
s.Group("/admin", func(r slim.RouteCollector) {
r.Use(middleware.BasicAuth(func(username, password string, c slim.Context) (bool, error) {
if username == "joe" && password == "secret" {
return true, nil
}
return false, nil
}))
})
// Route level middleware
track := func(c slim.Context, next slim.HandlerFunc) error {
println("request to /users")
return next(c)
}
route := s.GET("/users", func(c slim.Context) error {
return c.String(http.StatusOK, "/users")
})
route.Use(track)
// ... business logic
log.Fatal(s.Start(":1324"))
}
If you have used other web frameworks such as chi, echo, gin, etc., although they have the same route group concept, there is a fundamental difference:
- In these frameworks, during route declaration, the middleware of route groups is copied and merged to routes, and route groups are discarded after route declaration is complete.
- In our framework, route groups form a tree structure with routers and routes. During request processing, requests are passed down from top to bottom, and then responses are filtered and returned in reverse order, based on which a friendly and intuitive onion model is implemented.