add basic auth for webapi

This commit is contained in:
ginuerzh
2022-02-12 21:05:39 +08:00
parent fdd67a6086
commit f2d806886a
12 changed files with 197 additions and 86 deletions

13
cmd/gost/api.yaml Normal file
View File

@ -0,0 +1,13 @@
api:
addr: :18080
accesslog: true
pathPrefix: /api
auth:
username: gost
password: gost
auther: auther-0
authers:
- name: auther-0
auths:
- username: gost1
password: gost1

View File

@ -4,6 +4,7 @@ import (
"io"
"os"
"github.com/go-gost/gost/pkg/api"
"github.com/go-gost/gost/pkg/config"
"github.com/go-gost/gost/pkg/config/parsing"
"github.com/go-gost/gost/pkg/logger"
@ -11,8 +12,8 @@ import (
"github.com/go-gost/gost/pkg/service"
)
func buildService(cfg *config.Config) (services []*service.Service) {
if cfg == nil || len(cfg.Services) == 0 {
func buildService(cfg *config.Config) (services []service.Servicer) {
if cfg == nil {
return
}
@ -109,3 +110,16 @@ func logFromConfig(cfg *config.LogConfig) logger.Logger {
return logger.NewLogger(opts...)
}
func buildAPIServer(cfg *config.APIConfig) (*api.Server, error) {
auther := parsing.ParseAutherFromAuth(cfg.Auth)
if cfg.Auther != "" {
auther = registry.Auther().Get(cfg.Auther)
}
return api.NewServer(
cfg.Addr,
api.PathPrefixOption(cfg.PathPrefix),
api.AccessLogOption(cfg.AccessLog),
api.AutherOption(auther),
)
}

View File

@ -3,13 +3,11 @@ package main
import (
"flag"
"fmt"
"net"
"net/http"
_ "net/http/pprof"
"os"
"runtime"
"github.com/go-gost/gost/pkg/api"
"github.com/go-gost/gost/pkg/config"
"github.com/go-gost/gost/pkg/logger"
)
@ -93,17 +91,16 @@ func main() {
}()
}
if cfg.API != nil && cfg.API.Addr != "" {
api.Init(cfg.API)
ln, err := net.Listen("tcp", cfg.API.Addr)
if cfg.API != nil {
s, err := buildAPIServer(cfg.API)
if err != nil {
log.Fatal(err)
}
defer ln.Close()
defer s.Close()
go func() {
log.Info("api server on ", ln.Addr())
log.Fatal(api.Run(ln))
log.Info("api server on ", s.Addr())
log.Fatal(s.Serve())
}()
}
@ -111,7 +108,7 @@ func main() {
services := buildService(cfg)
for _, svc := range services {
go svc.Run()
go svc.Serve()
}
config.SetGlobal(cfg)