dashboard.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2016 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. "github.com/fatedier/frp/models/config"
  22. )
  23. var (
  24. httpServerReadTimeout = 10 * time.Second
  25. httpServerWriteTimeout = 10 * time.Second
  26. )
  27. func RunDashboardServer(addr string, port int64) (err error) {
  28. // url router
  29. mux := http.NewServeMux()
  30. // api, see dashboard_api.go
  31. //mux.HandleFunc("/api/reload", use(apiReload, basicAuth))
  32. //mux.HandleFunc("/api/proxies", apiProxies)
  33. // view, see dashboard_view.go
  34. mux.Handle("/favicon.ico", http.FileServer(assets.FileSystem))
  35. mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(assets.FileSystem)))
  36. //mux.HandleFunc("/", use(viewDashboard, basicAuth))
  37. address := fmt.Sprintf("%s:%d", addr, port)
  38. server := &http.Server{
  39. Addr: address,
  40. Handler: mux,
  41. ReadTimeout: httpServerReadTimeout,
  42. WriteTimeout: httpServerWriteTimeout,
  43. }
  44. if address == "" {
  45. address = ":http"
  46. }
  47. ln, err := net.Listen("tcp", address)
  48. if err != nil {
  49. return err
  50. }
  51. go server.Serve(ln)
  52. return
  53. }
  54. func use(h http.HandlerFunc, middleware ...func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc {
  55. for _, m := range middleware {
  56. h = m(h)
  57. }
  58. return h
  59. }
  60. func basicAuth(h http.HandlerFunc) http.HandlerFunc {
  61. return func(w http.ResponseWriter, r *http.Request) {
  62. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  63. username, passwd, ok := r.BasicAuth()
  64. if !ok {
  65. http.Error(w, "Not authorized", 401)
  66. return
  67. }
  68. if username != config.ServerCommonCfg.DashboardUser || passwd != config.ServerCommonCfg.DashboardPwd {
  69. http.Error(w, "Not authorized", 401)
  70. return
  71. }
  72. h.ServeHTTP(w, r)
  73. }
  74. }