This repository has been archived by the owner on Jan 29, 2024. It is now read-only.
/
api.go
60 lines (51 loc) · 1.44 KB
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package api
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/peizhong/letsgo/playground/proxy/kuproxy/proxy"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func ResponseJson(w http.ResponseWriter, obj interface{}) {
w.Header().Add("Content-Type", "application/json; charset=utf-8")
bytes, err := json.Marshal(obj)
if err != nil {
w.Write([]byte(err.Error()))
return
}
w.Write(bytes)
}
func ResponseError(w http.ResponseWriter, msg string, code int) {
http.Error(w, msg, code)
}
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
log.Println(r.RequestURI)
next.ServeHTTP(w, r)
})
}
func StartHttp(httpAddr string, rt *proxy.Runtime) {
r := mux.NewRouter()
// todo: 如果部署多个副本就用不了了
r.PathPrefix("/debug/pprof/").Handler(http.DefaultServeMux)
r.Handle("/metrics", promhttp.Handler())
admin := r.PathPrefix("/admin").Subrouter()
adminHandler := NewAdminHandler(rt)
admin.HandleFunc("/", adminHandler.Root)
admin.HandleFunc("/services/{serviceName}", adminHandler.ServiceEndpoints)
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
})
r.Use(LoggingMiddleware)
srv := &http.Server{
Addr: httpAddr,
Handler: r,
}
log.Println("http listen at", httpAddr)
err := srv.ListenAndServe()
if err != nil {
panic(err.Error())
}
}