github.com/vicanso/pike@v1.0.1-0.20210630235453-9099e041f6ec/test/main.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"time"
     8  
     9  	"github.com/vicanso/elton"
    10  	"golang.org/x/net/http2"
    11  	"golang.org/x/net/http2/h2c"
    12  )
    13  
    14  func httpGet(url string) (data []byte, err error) {
    15  	res, err := http.Get(url)
    16  	if err != nil {
    17  		return
    18  	}
    19  	defer res.Body.Close()
    20  	data, err = ioutil.ReadAll(res.Body)
    21  	if err != nil {
    22  		return
    23  	}
    24  	return
    25  }
    26  
    27  func main() {
    28  	e := elton.New()
    29  
    30  	e.GET("/repos", func(c *elton.Context) (err error) {
    31  		buf, err := httpGet("https://api.github.com/users/vicanso/repos")
    32  		if err != nil {
    33  			return
    34  		}
    35  		c.SetContentTypeByExt(".json")
    36  		c.CacheMaxAge(5 * time.Minute)
    37  		c.BodyBuffer = bytes.NewBuffer(buf)
    38  		return
    39  	})
    40  
    41  	e.GET("/ping", func(c *elton.Context) (err error) {
    42  		c.BodyBuffer = bytes.NewBufferString("pong")
    43  		return
    44  	})
    45  
    46  	// http1与http2均支持
    47  	e.Server = &http.Server{
    48  		Handler: h2c.NewHandler(e, &http2.Server{}),
    49  	}
    50  
    51  	err := e.ListenAndServe(":3001")
    52  	if err != nil {
    53  		panic(err)
    54  	}
    55  }