Gin-Use golang to write the front end

Gin

Quick access to gin

Installation method

$ go get -u github.com/gin-gonic/gin

import gin

import “github.com/gin-gonic/gin”

gin's first small project

package main

import (
	"github.com/gin-gonic/gin"
)

func Hello(c *gin.Context) {
    
    
	 c.String(200, "hello,go")
}

func main() {
    
    
	e := gin.Default()
	e.GET("/hello", Hello)
	e.Run()
}

Visit the page localhost:8080/hello to see hello, go

gin runs on port 8080 by default. We can see that gin is actually built based on httprouter. We can also restore the above logic using httprouter.

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/julienschmidt/httprouter"
)

func Hello(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    
    
	fmt.Fprintf(w, "hello,go")
}

func main() {
    
    
	router := httprouter.New()
	router.GET("/hello", Hello)
	log.Fatal(http.ListenAndServe(":8080", router))
}

But we can obviously find that using gin will be much more elegant

Use gin to simply write a login

In gin, we agreed to put all the html files that need to be used in the templates folder

Landing page login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        //方法名为post 因为我们需要用post方法调用提交功能,action为我们提交后需要跳转的位置
        <form action="/welcome" method="post">
            userName: <input type="text" class="text" name="userName"><br>
            passWord: <input type="password" name="password"><br>
            <input type="submit" value="提交">
        </form>
    </div>
    
</body>
</html>

Welcome.html interface entered after successful login

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>
        welcome {
   
   {.userName}}
    </p>
</body>
</html>

main.go

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
    
    
	c.HTML(http.StatusOK, "login.html", nil)
}

func DoWelcom(c *gin.Context) {
    
    
    //*gin.Context是gin中一个非常关键的上下文流
    // 为了拿到form内名为username输入框的内容
	userName := c.PostForm("userName")
	c.HTML(http.StatusOK, "welcome.html", gin.H{
    
    
	   //给welcone.html文件传递username
		"userName": userName,
	})
}

func main() {
    
    
	e := gin.Default()
	//获取html文件流
	e.LoadHTMLGlob("templates/*")
	e.GET("/login", Login)
	e.POST("/welcome", DoWelcom)
	e.Run()
}

gin GET

GET is actually a method of passing parameters, following the params after routing, the following method is similar to adding ? after the routing path? username=""&password="" 123 and 111 are the default data respectively

func testGet(c *gin.Context) {
    
    
	s := c.DefaultQuery("username", "123")
	password := c.DefaultQuery("password", "111")
	c.String(200, "username:%s,password:%s", s, password)
}

bind query parameters

Bind parameters within the form by defining a struct

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <form action="/regiester" method="post">
            userName: <input type="text" class="text" name="userName"><br>
            passWord: <input type="password" name="password"><br>

            爱好:
            <input type="checkbox" name="hobby" value="swmming" id="">游泳
            <input type="checkbox" name="hobby" value="run" id="">跑步
            <br>
            性别:
            <input type="radio" name="gender" value="1" id=""><input type="radio" name="gender" value="2" id="">
            城市
            <select name="city" id="">
                <option value="beijing">北京</option>
                <option value="shenzhen">深圳</option>
            </select>

            <input type="submit" value="提交">
        </form>
    </div>
    
</body>
</html>
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type User struct {
    
    
	UserName string   `form:"userName"`
	Password string   `form:"password"`
	Hobby    []string `form:"hobby"`
	Gender   string   `form:"gender"`
	City     string   `form:"city"`
}
func Regiester(c *gin.Context) {
    
    
	var user User
	c.ShouldBind(&user)
	c.String(200, "USER:%s", user)
}
func main() {
    
    
	e := gin.Default()
	e.LoadHTMLGlob("templates/*")
	e.GET("/login", Login)
	e.POST("/regiester", Regiester)
	e.Run()
}

gin to access static files such as bootstrap

  • First go to the bootstrap official website to download the bootstrap static resource package,
  • Create an assets folder in the project directory to store static resources, and put the css and js packages downloaded in bootstrap into this folder
  • Create a templates folder to store the html file, create an html file, and then use the link in the head tag to import the css file, and the script tag to import the js file. Here we recommend using the bootstrap.min package, which means small, so as to optimize our page load speed
  • Use gin to import the html file in the go file and mount it to port 8080

bootstrapExp.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <script src="../assets/js/bootstrap.min.js"></script>
</head>

<body>
    <label for="customRange1" class="form-label">Example range</label>
    <input type="range" class="form-range" id="customRange1">
</body>

</html>

main.go

package main

import "github.com/gin-gonic/gin"

func assents(c *gin.Context) {
    
    
	c.HTML(200, "bootstrapExp.html", nil)
}

func main() {
    
    
	e := gin.Default()
	e.LoadHTMLGlob("templates/*")
	e.GET("/assents", assents)
	e.Run()
}

Open localhost:8080/assents to see the bootstrap progress bar component we introduced

gin middleware

Middleware is a method that occurs in the middle of the construction after running, and can be used for data processing, interception, etc.

When we instantiate gin by default, the gin.Default() method used has actually loaded two middleware by default for us. Let's see how the Default method is composed

func Default() *Engine {
    
    
	debugPrintWARNINGDefault()
	engine := New()
	engine.Use(Logger(), Recovery())
	return engine
}

When the Default method creates a gin instance, the logger and recovert middleware are added by default

When we don't want to use these two middleware, we can initialize gin like this

e:= gin.New()

At this time, e does not have any middleware

Create a middleware yourself

Middleware is actually a method. To create a middleware is to create a method. We use the
Use() method. Passing the middleware method as a parameter to Use() is to mount the middleware.

package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

func testMiddleWare(c *gin.Context) {
    
    
	c.String(200, "hello,%s", "lyi")
}

func middleware1(c *gin.Context) {
    
    
	fmt.Printf("你好我是中间件1")
}
func midellware2(c *gin.Context) {
    
    
	fmt.Printf("你好我是中间件2")
}

func main() {
    
    
	e := gin.Default()
	e.Use(middleware1)
	e.GET("/middleware", testMiddleWare)
	e.Use(midellware2)
	e.Run()
}

We can see that middleware1 and middleware2 are before and after mounting. When running, we can only see the middleware before mounting, that is, the running result of middleware1.

[GIN-debug] GET    /middleware               --> main.testMiddleWare (4 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
你好我是中间件1[GIN] 2022/06/23 - 14:59:05 | 200 |      66.292µs |             ::1 | GET      "/middleware"

Using BasicAuth middleware

// 模拟一些私人数据
var secrets = gin.H{
    
    
	"foo":    gin.H{
    
    "email": "[email protected]", "phone": "123433"},
	"austin": gin.H{
    
    "email": "[email protected]", "phone": "666"},
	"lena":   gin.H{
    
    "email": "[email protected]", "phone": "523443"},
}

func main() {
    
    
	r := gin.Default()

	// 路由组使用 gin.BasicAuth() 中间件
	// gin.Accounts 是 map[string]string 的一种快捷方式
	authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
    
    
		"foo":    "bar",
		"austin": "1234",
		"lena":   "hello2",
		"manu":   "4321",
	}))

	// /admin/secrets 端点
	// 触发 "localhost:8080/admin/secrets
	authorized.GET("/secrets", func(c *gin.Context) {
    
    
		// 获取用户,它是由 BasicAuth 中间件设置的
		user := c.MustGet(gin.AuthUserKey).(string)
		if secret, ok := secrets[user]; ok {
    
    
			c.JSON(http.StatusOK, gin.H{
    
    "user": user, "secret": secret})
		} else {
    
    
			c.JSON(http.StatusOK, gin.H{
    
    "user": user, "secret": "NO SECRET :("})
		}
	})

	// 监听并在 0.0.0.0:8080 上启动服务
	r.Run(":8080")
}

Use cookies

package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

func main() {
    
    
	e := gin.Default()
	e.GET("/cookie", func(ctx *gin.Context) {
    
    
		s, err := ctx.Cookie("go_cookie")
		if err != nil {
    
    
			s = "no_cookie"
			ctx.SetCookie("go_cookie", //cookie名称
				s,           //cookie实例
				10,          //cookie保存时间,单位是s
				"/",         //路径
				"localhost", //域
				false,       //安全模式,如果开启,将只能通过https模式访问
				true,        //httpOnly
			)
		}
		fmt.Printf("s: %v\n", s)

	})
	e.Run()
}

Open the browser and we can find the cookie data in the console

Guess you like

Origin blog.csdn.net/weixin_44846765/article/details/125429295