Go language Web framework guide

brief introduction

wego is a high-performance Web framework written in Go language, which can be used to quickly develop various applications such as RESTful services and back-end services.
wego framework is a complete MVC framework, including routing module, database ORM module, view template processing and Session module.
wego has the characteristics of high performance, easy to use, good compatibility and strong scalability. The specific characteristics are as follows:

  1. The routing module developed based on Radix tree has high routing query performance.
  2. Support routing groups.
  3. It provides a convenient and easy-to-use API for the access rate of routing parameters, Query parameters and Form parameters, and can map parameters to Struct.
  4. Provides an easy-to-use API for JSON, XML, and HTML rendering.
  5. Support filter middleware to facilitate you to extend the Web framework.
  6. It supports BeforeRoute, BeforeExec and AfterExec interceptors to facilitate authentication and log output.
  7. With the built-in Crash processing mechanism, wego can recover the panic in an HTTP request, which can ensure that your server is always available.
  8. It is convenient to manage the built-in parameters of Config module.
  9. With the built-in Session module, you can choose cookie, redis, memcache and memory cache engine to store Session data.
  10. Built in ORM module (under development).
  11. The built-in log module is used to generate application logs.
  12. Using the cache to manage the HTML Template can not only facilitate the output of HTML pages, but also use the cache to improve the system performance.
  13. Good compatibility. Wego supports go's native func(http.ResponseWriter, *http.Request) routing processing function, so that your code can use wego with a small amount of modification.
  14. wego is compatible with two coding habits. You can use ordinary functions as routing processing functions or strcut member functions as routing processing functions.

install

go get github.com/haming123/wego

Simple http server

Create a main Go file with the following code:

package main
import (
	"wego"
	log "wego/dlog"
)
func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/hello", func(c *wego.WebContext) {
		c.WriteText(200, "world")
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

Then run it, open the browser, and enter http://localhost:8080/hello , you can see the following:

world

Project structure

The wego box does not limit the project structure. Here is a suggested structure of the MVC framework project:

demo
├── app             
│   └── router.go       - Routing profile
│   └── templfun.go     - Template function file
├── controllers         - The controller directory can be divided into subdirectories if necessary
│   └── controller_xxx.go
├── models              - Model catalog
│   └── model_xxx.go
├── logs                - Log file directory, which mainly saves the logs generated during the operation of the project
│   └── applog_20211203.log
├── static              - Static resource directory
│   ├── css
│   ├── img
│   └── js
├── utils               - Common code directory
│   └── util_xxx.go
├── views               - View template directory
│   └── html_xxx.html
├── app.conf            - Application profile
└── main.go             - Entry file

Register parameter routing

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.PATH("/user/:id", func(c *wego.WebContext) {
		c.WriteTextF(200, "param id=%s", c.RouteParam.GetString("id").Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

Register fuzzy matching route

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.PATH("/files/*name", func(c *wego.WebContext) {
		c.WriteTextF(200, "param name=%s", c.RouteParam.GetString("name").Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

Register RESTful routes

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/users/:id", func(c *wego.WebContext) {
		//Query a user
	})
	web.POST("/users/:id", func(c *wego.WebContext) {
		//Create a user
	})
	web.PUT("/users/:id", func(c *wego.WebContext) {
		//Update user information
	})
	web.PATCH("/users/:id", func(c *wego.WebContext) {
		//Update some information of users
	})
	web.DELETE("/users/:id", func(c *wego.WebContext) {
		//delete user
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

Get parameters

Pass c.param. In wego Getxxx function to get request parameters:

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/user", func(c *WebContext) {
		name := c.Param.GetString("name")
		if name.Error != nil {
			t.Error(name.Error)
		}
		age := c.Param.GetInt("age")
		if age.Error != nil {
			t.Error(age.Error)
		}
        c.WriteText(200, name.Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

Get parameters using MustXXX convenience function

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/user", func(c *WebContext) {
		name := c.Param.MustString("name")
		t.Log(name)
		age := c.Param.MustInt("age")
		t.Log(age)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

Get parameters using ReadJSON

If the data format of the Body in the POST request is JSON format, you can directly use the ReadJSON function of WebContext to read:

func main() {
   web, err := wego.NewWeb()
   if err != nil{
   	log.Error(err)
   	return
   }

   web.POST("/user", func(c *WebContext) {
   	var user2 User
   	err := c.ReadJSON(&user2)
   	if err != nil {
   		t.Log(err)
   	}
   	t.Log(user2)
   })

   err = web.Run(":8080")
   if err != nil {
   	log.Error(err)
   }
}

Output JSON data

wego supports JSON very well, which makes it very convenient for us to develop an API based on JSON. To return the result of a JSON request, you can use the WriteJSON function:

func writeJson(c *wego.WebContext) {
	var user User
	user.ID = 1
	user.Name = "demo"
	user.Age = 12
	c.WriteJSON(200, user)
}

Output HTML data

The output of html results of wego framework is implemented based on html/template. The following is an example of outputting an html page:

func writeHtml(c *wego.WebContext) {
	var user User
	user.ID = 1
	user.Name = "demo"
	user.Age = 12
	c.WriteHTML(200, "./views/index.html", user)
}

Using template functions

If template functions are used in your template file, you need to register the required template functions in advance:

func GetUserID(id int64) string {
	return fmt.Sprintf("ID_%d", id)
}

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	wego.AddTemplFunc("GetUserID", GetUserID)
	web.GET("/templfunc", (c *wego.WebContext) {
        var user User
        user.ID = 1
        user.Name = "lisi"
        user.Age = 12
        c.WriteHTML(200, "./views/index.html", user)
     })

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

Set cookie s

func setCookie(c *wego.WebContext)  {
	val, err := c.Input.Cookie("demo")
	if err != nil {
		log.Error(err)
	}
	cookie := &http.Cookie{
		Name:     "demo",
		Value:    "test",
		Path:     "/",
		HttpOnly: true,
	}
	c.SetCookie(cookie)
}

redirect

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/redirect", func(c *wego.WebContext) {
		c.Redirect(302, "/index")
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

error handling

func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/abort", func(c *wego.WebContext) {
		name := c.Param.GetString("name")
		if name.Error != nil {
			c.AbortWithError(500, name.Error)
			return
		}
		c.WriteText(200, "hello " + name.Value)
	})

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}

Use profile

  • First, define a simple configuration file
#apply name
app_name = demo
#Configuration parameters of mysql database
mysql = root:rootpwd@tcp(127.0.0.1:3306)/demp?charset=utf8

[server]
#http listening port
http_port = 8080
  • Use the InitWeb() function to initialize the Web server
func main() {
    web, err := wego.InitWeb()
	if err != nil{
		log.Error(err)
		return
	}

	err = web.Run()
	if err != nil {
		log.Error(err)
	}
}

Note: when calling InitWeb() function, you can specify a configuration file. If no configuration file is specified, the default configuration file will be used:/ app.conf.

Get business parameters

After calling InitWeb(), wego will automatically resolve the system parameters to webengine In config, the user needs to call the GetXXX function of the configuration data to obtain the business parameters. For example:

func main() {
	web, err := wego.InitWeb()
	if err != nil{
		log.Error(err)
		return
	}

	mysql_cnn := web.Config.GetString("mysql")
	if mysql_cnn.Error != nil {
		log.Error(mysql_cnn.Error)
		return
	}
	log.Info(mysql_cnn.Value)

	err = web.Run()
	if err != nil {
		log.Error(err)
	}
}

Using Session

  • Preferred definition profile:
#apply name
app_name = demo

[server]
#http listening port
http_port = 8080

[session]
#Whether the session is enabled
session_on = true
#session type: cookie, cache
session_store=cookie
#The name of the client's cookie
cookie_name = "wego"
#session expiration time, in seconds
life_time = 3600
#hash string of session data
hash_key = demohash
  • Then load the configuration file in the entry function
func main() {
	web, err := wego.NewWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET("/login", login)
	web.GET("/index", index)

	err = web.Run(":8080")
	if err != nil {
		log.Error(err)
	}
}
  • Then save the session data in the login processor function:
func login(c *wego.WebContext)  {
	c.Session.Set("uid", 1)
	c.Session.Save()
	c.Redirect(302, "/index")
}
  • Then the session data can be accessed in the index processor function:
func index(c *wego.WebContext)  {
	id , _ := c.Session.GetInt("uid")
	c.WriteTextF(200, "uid=%d", id)
}

Output log

package main
import log "wego/dlog"
func main()  {
	log.Debug("This is a Debug Message")
	log.Info("This is a Info Message")
}
//The output result after execution is:
//2021/11/30 07:20:06 [D] main.go:31 This is a Debug Message
//2021/11/30 07:20:06 [I] main.go:32 This is a Debug Info

Keywords: Go

Added by Horizon88 on Fri, 18 Feb 2022 18:45:24 +0200