Slim

Quick Start

Installation

To install Slim, Go 1.21.0 or higher is required.

Initialize project
$ 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.

Regular instance
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

server.go
package mainimport (    "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

terminal
$ go run server.go

Open the URL http://localhost:1324, and we can see the string Hello, World! on the page.

Routing

Define RESTful routes
s.POST("/users", saveUser)s.GET("/users/:id", getUser)s.PUT("/users/:id", updateUser)s.DELETE("/users/:id", deleteUser)

Path Parameters

Handle 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

Handle 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:

namevalue
nameJoe Smith
emailjoe@go-slim.dev
Handle form data
// 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:

Terminal
$ 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:

namevalue
nameJoe Smith
avataran avatar file
Handle file upload
// 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:

Terminal
$ 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:

Terminal
$ cd <project directory>$ ls avatar.png// => avatar.png

Handling Requests

  • Call the method Context#Bind, and Slim will bind submitted json, xml, form, query, header, and other data to Go structs based on the value of the request header Content-Type.
  • Respond with HTTP status code and render json, xml, or other formats of data.
Request handler
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/.

Static service route
s.Static("/static", "static")

Template Rendering

The template rendering interface needs to be implemented in advance.

Middleware

Middleware example
package mainimport (    "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"))}
Tip

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.
Navigate Select esc Close search