dashboard.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package server
  15. import (
  16. "fmt"
  17. "net"
  18. "net/http"
  19. "time"
  20. "github.com/fatedier/frp/assets"
  21. frpNet "github.com/fatedier/frp/utils/net"
  22. "github.com/gorilla/mux"
  23. "github.com/prometheus/client_golang/prometheus/promhttp"
  24. )
  25. var (
  26. httpServerReadTimeout = 10 * time.Second
  27. httpServerWriteTimeout = 10 * time.Second
  28. )
  29. func (svr *Service) RunDashboardServer(addr string, port int) (err error) {
  30. // url router
  31. router := mux.NewRouter()
  32. user, passwd := svr.cfg.DashboardUser, svr.cfg.DashboardPwd
  33. router.Use(frpNet.NewHttpAuthMiddleware(user, passwd).Middleware)
  34. // metrics
  35. if svr.cfg.EnablePrometheus {
  36. router.Handle("/metrics", promhttp.Handler())
  37. }
  38. // api, see dashboard_api.go
  39. router.HandleFunc("/api/serverinfo", svr.ApiServerInfo).Methods("GET")
  40. router.HandleFunc("/api/proxy/{type}", svr.ApiProxyByType).Methods("GET")
  41. router.HandleFunc("/api/proxy/{type}/{name}", svr.ApiProxyByTypeAndName).Methods("GET")
  42. router.HandleFunc("/api/traffic/{name}", svr.ApiProxyTraffic).Methods("GET")
  43. // view
  44. router.Handle("/favicon.ico", http.FileServer(assets.FileSystem)).Methods("GET")
  45. router.PathPrefix("/static/").Handler(frpNet.MakeHttpGzipHandler(http.StripPrefix("/static/", http.FileServer(assets.FileSystem)))).Methods("GET")
  46. router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  47. http.Redirect(w, r, "/static/", http.StatusMovedPermanently)
  48. })
  49. address := fmt.Sprintf("%s:%d", addr, port)
  50. server := &http.Server{
  51. Addr: address,
  52. Handler: router,
  53. ReadTimeout: httpServerReadTimeout,
  54. WriteTimeout: httpServerWriteTimeout,
  55. }
  56. if address == "" {
  57. address = ":http"
  58. }
  59. ln, err := net.Listen("tcp", address)
  60. if err != nil {
  61. return err
  62. }
  63. go server.Serve(ln)
  64. return
  65. }