12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package agent
- import (
- "encoding/json"
- "fmt"
- "net/http"
- "time"
- "github.com/prometheus/client_golang/prometheus/promhttp"
- "go-common/library/log"
- )
- type HTTPServer struct {
- *http.Server
- agent *Agent
-
- proto string
- }
- func NewHTTPServer(addr string, a *Agent) *HTTPServer {
- s := &HTTPServer{
- Server: &http.Server{Addr: addr},
- agent: a,
- }
- s.Server.Handler = s.handler()
- return s
- }
- func (s *HTTPServer) handler() http.Handler {
- mux := http.NewServeMux()
-
-
- mux.HandleFunc("/v1/naming/", s.wrap(s.NSTranslation))
- mux.Handle("/metrics", promhttp.Handler())
- return mux
- }
- func (s *HTTPServer) wrap(handler func(resp http.ResponseWriter, req *http.Request) (interface{}, error)) http.HandlerFunc {
- return func(resp http.ResponseWriter, req *http.Request) {
- logURL := req.URL.String()
- handleErr := func(err error) {
- log.Error("http: Request %s %v from %s, err: %v\n", req.Method, logURL, req.RemoteAddr, err)
- resp.WriteHeader(http.StatusInternalServerError)
- fmt.Fprint(resp, err.Error())
- }
-
- start := time.Now()
- defer func() {
- log.V(5).Info("http: Request %s %v from %s, Timing: %v\n", req.Method, logURL, req.RemoteAddr, time.Since(start))
- }()
- obj, err := handler(resp, req)
- if err != nil {
- handleErr(err)
- return
- }
- if obj == nil {
- return
- }
- buf, err := s.marshalJSON(req, obj)
- if err != nil {
- handleErr(err)
- return
- }
- resp.Header().Set("Content-Type", "application/json")
- resp.Write(buf)
- }
- }
- func (s *HTTPServer) marshalJSON(req *http.Request, obj interface{}) ([]byte, error) {
- if _, ok := req.URL.Query()["pretty"]; ok {
- buf, err := json.MarshalIndent(obj, "", " ")
- if err != nil {
- return nil, err
- }
- buf = append(buf, "\n"...)
- return buf, nil
- }
- buf, err := json.Marshal(obj)
- if err != nil {
- return nil, err
- }
- return buf, err
- }
|