-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: init web framework implement (#88)
## What type of PR is this? /kind feature ## What this PR does / why we need it: Implement a web framework, including: * Automatically inject `requestID`, `auditLogger`, `bizLogger` * Support automatic recovery when api call panic * 100% compatible with standard library(`net/http`) * Except for `go-chi/chi`, there is no indirect dependence
- Loading branch information
Showing
9 changed files
with
268 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// Copyright The Karbour Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package config | ||
|
||
import ( | ||
"encoding/json" | ||
"net/http" | ||
|
||
"github.com/KusionStack/karbour/pkg/controller/config" | ||
"github.com/KusionStack/karbour/pkg/util/ctxutil" | ||
) | ||
|
||
func Get(configCtrl *config.Controller) http.HandlerFunc { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
log := ctxutil.GetLogger(r.Context()) | ||
|
||
log.Info("Starting get config ...") | ||
|
||
b, err := json.MarshalIndent(configCtrl.Get(), "", " ") | ||
if err != nil { | ||
log.Error(err, "Failed to mashal json") | ||
http.Error(w, "Internal server error", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
w.Write(b) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
// Copyright The Karbour Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package apiserver | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"strings" | ||
|
||
confighandler "github.com/KusionStack/karbour/pkg/apis/config" | ||
"github.com/KusionStack/karbour/pkg/controller/config" | ||
appmiddleware "github.com/KusionStack/karbour/pkg/middleware" | ||
"github.com/go-chi/chi/v5" | ||
"github.com/go-chi/chi/v5/middleware" | ||
"k8s.io/klog/v2" | ||
) | ||
|
||
// DefaultStaticDirectory is the default static directory for | ||
// dashboard. | ||
const DefaultStaticDirectory = "./static" | ||
|
||
func NewCoreAPIs() http.Handler { | ||
router := chi.NewRouter() | ||
|
||
// Set up middlewares | ||
router.Use(middleware.RequestID) | ||
router.Use(appmiddleware.AuditLogger) | ||
router.Use(appmiddleware.APILogger) | ||
router.Use(middleware.Recoverer) | ||
|
||
// Set up the frontend router | ||
klog.Infof("Dashboard's static directory use: %s", DefaultStaticDirectory) | ||
router.NotFound(http.FileServer(http.Dir(DefaultStaticDirectory)).ServeHTTP) | ||
|
||
// Set up the core api router | ||
configCtrl := config.NewController(&config.Config{ | ||
Verbose: false, | ||
}) | ||
|
||
router.Route("/api/v1", func(r chi.Router) { | ||
setupAPIV1(r, configCtrl) | ||
}) | ||
|
||
router.Get("/endpoints", func(w http.ResponseWriter, req *http.Request) { | ||
endpoints := listEndpoints(router) | ||
w.Header().Set("Content-Type", "text/plain") | ||
w.Write([]byte(strings.Join(endpoints, "\n"))) | ||
}) | ||
|
||
return router | ||
} | ||
|
||
func setupAPIV1(r chi.Router, configCtrl *config.Controller) { | ||
r.Route("/config", func(r chi.Router) { | ||
r.Get("/", confighandler.Get(configCtrl)) | ||
// r.Delete("/", confighandler.Delete(configCtrl)) | ||
// r.Post("/", confighandler.Post(configCtrl)) | ||
// r.Put("/", confighandler.Put(configCtrl)) | ||
}) | ||
|
||
// r.Route("/topology", func(r chi.Router) { | ||
// r.Get("/", topologyhandler.Get(topologyCtrl)) | ||
// r.Delete("/", topologyhandler.Delete(topologyCtrl)) | ||
// r.Post("/", topologyhandler.Post(topologyCtrl)) | ||
// r.Put("/", topologyhandler.Put(topologyCtrl)) | ||
// }) | ||
} | ||
|
||
func listEndpoints(r chi.Router) []string { | ||
var endpoints []string | ||
walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { | ||
endpoint := fmt.Sprintf("%s %s", method, route) | ||
endpoints = append(endpoints, endpoint) | ||
return nil | ||
} | ||
if err := chi.Walk(r, walkFunc); err != nil { | ||
fmt.Printf("Walking routes error: %s\n", err.Error()) | ||
} | ||
return endpoints | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
// Copyright The Karbour Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package config | ||
|
||
type Controller struct { | ||
config *Config | ||
} | ||
|
||
func NewController(config *Config) *Controller { | ||
return &Controller{ | ||
config: config, | ||
} | ||
} | ||
|
||
func (c *Controller) Get() *Config { | ||
return c.config | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
// Copyright The Karbour Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package config | ||
|
||
type Config struct { | ||
Verbose bool `json:"verbose"` | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
// Copyright The Karbour Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package middleware | ||
|
||
import ( | ||
"context" | ||
"net/http" | ||
|
||
"github.com/go-chi/chi/v5/middleware" | ||
"k8s.io/klog/v2" | ||
) | ||
|
||
type contextKey struct { | ||
name string | ||
} | ||
|
||
var APILoggerKey = &contextKey{"logger"} | ||
|
||
func APILogger(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
ctx := r.Context() | ||
|
||
if requestID := middleware.GetReqID(r.Context()); len(requestID) > 0 { | ||
logger := klog.FromContext(r.Context()). | ||
WithValues("requestID", requestID). | ||
WithValues("endpoint", r.RequestURI) | ||
ctx = context.WithValue(r.Context(), APILoggerKey, logger) | ||
} | ||
|
||
// continue serving request | ||
next.ServeHTTP(w, r.WithContext(ctx)) | ||
}) | ||
} | ||
|
||
func AuditLogger(next http.Handler) http.Handler { | ||
return middleware.Logger(next) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
// Copyright The Karbour Authors. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package ctxutil | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/KusionStack/karbour/pkg/middleware" | ||
"k8s.io/klog/v2" | ||
) | ||
|
||
// GetLogger returns the logger from the given context. | ||
// | ||
// Example: | ||
// | ||
// logger := ctxutil.GetLogger(ctx) | ||
func GetLogger(ctx context.Context) klog.Logger { | ||
if logger, ok := ctx.Value(middleware.APILoggerKey).(klog.Logger); ok { | ||
return logger | ||
} | ||
|
||
return klog.NewKlogr() | ||
} |