1.静态文件服务
1.1 代码
1 2 3 4 5 6 7 8 9 10 11
   | package main import "github.com/gin-gonic/gin" func main() { 	engine := gin.Default() 	 	engine.Static("/img","./public/img") 	 	engine.StaticFile("/favicon.ico","./public/favicon.ico") 	 	_ = engine.Run() }
 
  | 
 
1.2 目录结构

1.3 请求示例
1 2 3 4 5
   |  http://127.0.0.1:8080/img/b.jpg http://127.0.0.1:8080/img/c.jpg
  http://127.0.0.1:8080/favicon.ico
 
  | 
 
2.重定向
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   | package main import ( 	"github.com/gin-gonic/gin" 	"net/http" ) func main() { 	engine := gin.Default() 	 	engine.GET("/baidu", func(context *gin.Context) { 		context.Redirect(http.StatusMovedPermanently,"http://www.baidu.com") 	}) 	 	engine.GET("/route", func(context *gin.Context) { 		context.Request.URL.Path = "/baidu" 		engine.HandleContext(context) 	})
  	 	engine.GET("/pos", func(context *gin.Context) { 		context.Redirect(http.StatusTemporaryRedirect,"/get") 	}) 	engine.GET("/get", func(context *gin.Context) { 		context.JSON(http.StatusOK,gin.H{"msg":"success"}) 	}) 	 	_ = engine.Run() }
 
  | 
 
3.修改HTTP配置
3.1 默认启动HTTP服务
1 2 3 4 5 6 7 8 9
   | func main() { 	engine := gin.Default() 	 	engine.GET("/", func(context *gin.Context) { 		 	}) 	 	_ = engine.Run() }
 
  | 
 
3.2 启动自定义HTTP服务
可以直接使用 http.ListenAndServe()启动服务,具体配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
   | package main import ( 	"github.com/gin-gonic/gin" 	"net/http" 	"time" ) func main() { 	engine := gin.Default() 	 	serverConfig := &http.Server{ 		Addr: ":8080",  		Handler: engine, 		ReadTimeout: time.Second, 		WriteTimeout: time.Second, 		MaxHeaderBytes: 1 << 20, 	} 	 	engine.GET("/test", func(context *gin.Context) { 		context.JSON(200,gin.H{"msg":"success"}) 	}) 	 	_ = serverConfig.ListenAndServe() }
 
  | 
 
4.运行多个服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
   | package main
  import ( 	"golang.org/x/sync/errgroup" 	"log" 	"net/http" 	"github.com/gin-gonic/gin" 	"time" )
  var ( 	g errgroup.Group )
  func serverOne() http.Handler { 	engine := gin.Default() 	engine.GET("/server1", func(context *gin.Context) { 		context.JSON(200,gin.H{"msg":"server1"}) 	}) 	return engine }
  func serverTwo() http.Handler { 	engine := gin.Default() 	engine.GET("/server2", func(context *gin.Context) { 		context.JSON(200,gin.H{"msg":"server2"}) 	}) 	return engine } func main() { 	 	s1 := &http.Server{ 		Addr: ":8080", 		Handler: serverOne(), 		ReadTimeout: 5 * time.Second, 		WriteTimeout: 10 * time.Second, 	} 	 	s2 := &http.Server{ 		Addr: ":8081", 		Handler: serverTwo(), 		ReadTimeout: 5 * time.Second, 		WriteTimeout: 10 * time.Second, 	} 	 	g.Go(func() error { 		return s1.ListenAndServe() 	}) 	g.Go(func() error { 		return s2.ListenAndServe() 	}) 	if err := g.Wait();err != nil { 		log.Fatal(err) 	} }
 
  |