github.com/GuanceCloud/cliutils@v1.1.21/testutil/http.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package testutil 7 8 import ( 9 "context" 10 "net/http" 11 "testing" 12 13 "github.com/gin-gonic/gin" 14 ) 15 16 type HTTPServerOptions struct { 17 Bind string 18 Exit chan interface{} 19 20 SSL bool 21 CrtFile string 22 KeyFile string 23 24 Routes map[string]func(*gin.Context) 25 } 26 27 func NewHTTPServer(t *testing.T, opt *HTTPServerOptions) { 28 t.Helper() 29 30 r := gin.New() 31 r.Use(gin.Recovery()) 32 33 if opt == nil { 34 t.Errorf("invalid HTTPServerOptions") 35 return 36 } 37 38 for k, v := range opt.Routes { 39 r.Any(k, v) 40 } 41 42 srv := &http.Server{ 43 Addr: opt.Bind, 44 Handler: r, 45 } 46 47 go func() { 48 if opt.SSL { 49 if err := srv.ListenAndServeTLS(opt.CrtFile, opt.KeyFile); err != nil { 50 t.Errorf("ListenAndServeTLS(): %v", err) 51 } 52 } else { 53 if err := srv.ListenAndServe(); err != nil { 54 if err != http.ErrServerClosed { 55 t.Errorf("ListenAndServe(): %v", err) 56 return 57 } 58 t.Log(err) 59 } 60 } 61 }() 62 63 if opt.Exit != nil { 64 <-opt.Exit 65 _ = srv.Shutdown(context.Background()) 66 } 67 }