http http1.1ssl http2 http3 server only exemple
Closed this issue · 3 comments
itwars commented
Hi,
You really do a GREAT JOB!
My goal is to have:
- a http to https redirect (can't figure out how to do it)
- a http2 + http3 server (I can't figure out even by reading the example provide in markdown file)
package main
import (
"crypto/tls"
"os"
"regexp"
"time"
"github.com/vicanso/elton"
"github.com/vicanso/elton/middleware"
)
func getCert() (cert []byte, key []byte, err error) {
cert, err = os.ReadFile("server.crt")
if err != nil {
return
}
key, err = os.ReadFile("server.key")
if err != nil {
return
}
return
}
func main() {
e2 := elton.New()
// Gzip + Br compression
cfgCompress := middleware.NewCompressConfig(new(middleware.GzipCompressor), new(middleware.BrCompressor))
// Br compression only
//cfgCompress := middleware.NewCompressConfig(new(middleware.BrCompressor))
cfgCompress.Checker = regexp.MustCompile("svg|text|javascript|json|html|css|xml")
e2.Use(middleware.NewCompress(cfgCompress))
cert, key, err := getCert()
if err != nil {
panic(err)
}
tlsConfig := &tls.Config{}
tlsConfig.Certificates = make([]tls.Certificate, 1)
tlsConfig.Certificates[0], err = tls.X509KeyPair(cert, key)
if err != nil {
panic(err)
}
e2.Server.TLSConfig = tlsConfig
sf := new(middleware.FS)
e2.GET("/", func(c *elton.Context) (err error) {
r, err := sf.NewReader("static" + "/index.html")
if err != nil {
return
}
c.SetContentTypeByExt(".html")
c.Body = r
return
})
e2.GET("/*", middleware.NewStaticServe(sf, middleware.StaticServeConfig{
Path: "static",
MaxAge: 365 * 24 * time.Hour,
SMaxAge: time.Hour,
DenyDot: true,
EnableStrongETag: true,
}))
err = e2.ListenAndServeTLS(":443", "", "")
if err != nil {
panic(err)
}
}
Could you help me?
Thanks.
vicanso commented
- You can use like this:
package main
import (
"bytes"
"fmt"
"github.com/vicanso/elton"
)
func main() {
e := elton.New()
e.Use(func(ctx *elton.Context) error {
// is http
if ctx.Request.TLS == nil {
ctx.Redirect(301, "https://yourhost"+ctx.Request.RequestURI)
return nil
}
return ctx.Next()
})
e.GET("/ping", func(ctx *elton.Context) error {
ctx.BodyBuffer = bytes.NewBufferString("pong")
return nil
})
e.ALL("/*", func(ctx *elton.Context) error {
return nil
})
// http 80
go func() {
err := e.ListenAndServe(":80")
fmt.Println(err)
}()
// https 443
err := e.ListenAndServeTLS(":443", "", "")
fmt.Println(err)
}
- Do you try this example, htt2_http3
itwars commented
Sorry for my late answer.
- Your above code give me an error on open ?
- Issue with golang and http3 version on build...
vicanso commented
Question 1:
Please use the cert file and key file for tls:
err := e.ListenAndServeTLS(":443", certFile, keyFile)
Question 2, please show me more information.