Skip to content

Commit

Permalink
feat: nginx解析器支持设置alt-svc
Browse files Browse the repository at this point in the history
  • Loading branch information
devhaozi committed Oct 25, 2024
1 parent 2491f34 commit 9ac5ae4
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pkg/nginx/getter.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,21 @@ func (p *Parser) GetHTTPSRedirect() bool {
return false
}

func (p *Parser) GetAltSvc() string {
directive, err := p.FindOne("server.add_header")
if err != nil {
return ""
}

for i, param := range directive.GetParameters() {
if strings.HasPrefix(param, "Alt-Svc") && i+1 < len(directive.GetParameters()) {
return directive.GetParameters()[i+1]
}
}

return ""
}

func (p *Parser) GetAccessLog() (string, error) {
directive, err := p.FindOne("server.access_log")
if err != nil {
Expand Down
11 changes: 11 additions & 0 deletions pkg/nginx/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,17 @@ func (s *NginxTestSuite) TestHTTPSRedirect() {
s.False(parser.GetHTTPSRedirect())
}

func (s *NginxTestSuite) TestAltSvc() {
parser, err := NewParser()
s.NoError(err)
s.NoError(parser.SetHTTPS("/www/server/vhost/cert/default.pem", "/www/server/vhost/cert/default.key"))
s.Equal("", parser.GetAltSvc())
s.NoError(parser.SetAltSvc(`'h3=":$server_port"; ma=2592000'`))
s.Equal(`'h3=":$server_port"; ma=2592000'`, parser.GetAltSvc())
s.NoError(parser.SetAltSvc(""))
s.Equal("", parser.GetAltSvc())
}

func (s *NginxTestSuite) TestAccessLog() {
parser, err := NewParser()
s.NoError(err)
Expand Down
38 changes: 38 additions & 0 deletions pkg/nginx/setter.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,44 @@ func (p *Parser) SetHTTPRedirect(httpRedirect bool) error {
return p.Set("server", directives)
}

func (p *Parser) SetAltSvc(altSvc string) error {
old, err := p.Find("server.add_header")
if err != nil {
return err
}
if err = p.Clear("server.add_header"); err != nil {
return err
}

var directives []*config.Directive
var foundFlag bool
for _, dir := range old {
if slices.Contains(dir.GetParameters(), "Alt-Svc") {
foundFlag = true
directives = append(directives, &config.Directive{
Name: dir.GetName(),
Parameters: []string{"Alt-Svc", altSvc},
Comment: dir.GetComment(),
})
} else {
directives = append(directives, &config.Directive{
Name: dir.GetName(),
Parameters: dir.GetParameters(),
Comment: dir.GetComment(),
})
}
}

if !foundFlag && altSvc != "" {
directives = append(directives, &config.Directive{
Name: "add_header",
Parameters: []string{"Alt-Svc", altSvc},
})
}

return p.Set("server", directives)
}

func (p *Parser) SetAccessLog(accessLog string) error {
if err := p.Clear("server.access_log"); err != nil {
return err
Expand Down

0 comments on commit 9ac5ae4

Please sign in to comment.