forked from mmatczuk/go-http-tunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
61 lines (52 loc) · 1.42 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
61
// Copyright (C) 2021 Tribus Hannes
// Use of this source code is governed by an AGPL-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"fmt"
"net/http"
tunnel "github.com/hons82/go-http-tunnel"
"github.com/hons82/go-http-tunnel/log"
)
// ApiConfig defines configuration for the API.
type ApiConfig struct {
// Addr is TCP address to listen for client connections. If empty ":0" is used.
Addr string
//
Server *tunnel.Server
// Logger is optional logger. If nil logging is disabled.
Logger log.Logger
}
func initAPIServer(config *ApiConfig) {
logger := config.Logger
if logger == nil {
logger = log.NewNopLogger()
}
http.HandleFunc("/api/clients/list", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
logger.Log(
"level", 2,
"action", "start client list",
)
info := config.Server.GetClientInfo()
data, err := json.Marshal(info)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
e := fmt.Sprintf("Error on unmarshall item %s", err)
w.Write([]byte(e))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(data)
logger.Log(
"level", 3,
"action", "transferred",
"bytes", len(data),
)
},
))
// Wrap our server with our gzip handler to gzip compress all responses.
fatal("can not listen on: %s", http.ListenAndServe(config.Addr, nil))
}