1. 程式人生 > >golangWeb框架---github.com/gin-gonic/gin學習七(重定向、中介軟體Goroutines、http自定義配置)

golangWeb框架---github.com/gin-gonic/gin學習七(重定向、中介軟體Goroutines、http自定義配置)

重定向

package main

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

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

	router.GET("/raw", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently,"http://baidu.com")
	})
	router.Run(":8080")
}

瀏覽器輸入http://127.0.0.1:8080/raw,回車,神奇的跳轉到百度介面

伺服器內部重定向

我們還可以通過如下的寫法來實現

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

	router.GET("/test", func(c *gin.Context) {
		c.Request.URL.Path = "/test2"
		router.HandleContext(c)
	})
	router.GET("/test2", func(c *gin.Context) {
		c.JSON(200, gin.H{"hello": "world"})
	})

	router.Run(":8080")
}

上效果圖:
在這裡插入圖片描述

中介軟體

package main

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

func main() {
	r := gin.New()
	r.Use(Logger())

	r.GET("/test", func(c *gin.Context) {
		example := c.MustGet("example").(string)
		log.Println(example)
	})
	r.Run(":8080")
}

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()
		c.Set("example", "12345")
		c.Next()
		
		latency := time.Since(t)
		log.Print(latency)

		status := c.Writer.Status()
		log.Println(status)
	}
}

瀏覽器輸入http://127.0.0.1:8080/test
log日誌如下:

2018/09/21 15:44:24 12345
2018/09/21 15:44:24 131.006µs
2018/09/21 15:44:24 200

中介軟體內部的Goroutines

在中介軟體或處理程式中啟動新的Goroutine時,不應該使用其中的原始上下文,必須使用只讀副本

package main

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

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

	r.GET("/long_async", func(c *gin.Context) {
		// create copy to be used inside the goroutine
		cCp := c.Copy()
		go func() {
			// simulate a long task with time.Sleep(). 5 seconds
			time.Sleep(5 * time.Second)

			// note that you are using the copied context "cCp", IMPORTANT
			log.Println("Done! in path " + cCp.Request.URL.Path)
		}()
	})

	r.GET("/long_sync", func(c *gin.Context) {
		// simulate a long task with time.Sleep(). 5 seconds
		time.Sleep(5 * time.Second)

		// since we are NOT using a goroutine, we do not have to copy the context
		log.Println("Done! in path " + c.Request.URL.Path)
	})

	// Listen and serve on 0.0.0.0:8080
	r.Run(":8080")
}

瀏覽器發起請求,log日誌輸出

[GIN] 2018/09/21 - 17:40:20 | 200 |       2.451µs |       127.0.0.1 | GET      /long_async
2018/09/21 17:40:25 Done! in path /long_async
[GIN] 2018/09/21 - 17:40:36 | 200 |  5.003324304s |       127.0.0.1 | GET      /long_sync
2018/09/21 17:40:36 Done! in path /long_sync

HTTP自定義配置

    func main() {
    	router := gin.Default()
    	http.ListenAndServe(":8080", router)
    }

或者

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

	s := &http.Server{
		Addr:           ":8080",
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	s.ListenAndServe()
}