-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremoteip.go
107 lines (85 loc) · 2.05 KB
/
remoteip.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net"
"strings"
"github.com/buaazp/fasthttprouter"
"github.com/caarlos0/env"
"github.com/mindc/remoteip/api"
"github.com/valyala/fasthttp"
)
var (
// Version holds app version, filled at compile time
Version string
// BUILD holds app build version from git
BUILD string
)
var htdoc string
// Start handling default start page
func Start(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("text/html")
fmt.Fprint(ctx, strings.Replace(htdoc, "8.8.8.8", api.GetIP(ctx), -1))
}
// Config holds configuration strings
type Config struct {
Port string `env:"PORT" envDefault:"8080"`
PortSSL string `env:"PORT_SSL"`
HtDoc string `env:"HTDOC"`
SSLCert string `env:"SSL_CERT"`
SSLKey string `env:"SSL_KEY"`
}
func main() {
fmt.Printf("Version: %s\n", Version)
fmt.Printf("Build: %s\n", BUILD)
//read configuration from ENV
cfg := Config{}
err := env.Parse(&cfg)
if err != nil {
fmt.Printf("%#v\n", err)
}
fmt.Printf("%#v\n", cfg)
//read default htdoc
if len(cfg.HtDoc) > 0 {
fh, err := ioutil.ReadFile(cfg.HtDoc)
if err != nil {
log.Fatal(err)
}
htdoc = string(fh)
} else {
htdoc = "It works!"
}
//configure router
router := fasthttprouter.New()
router.GET("/", Start)
router.GET("/plain", api.Plain)
router.POST("/plain", api.Plain)
router.GET("/json", api.JSON)
router.POST("/json", api.JSON)
router.GET("/jsonp", api.JSONP)
router.POST("/jsonrpc", api.JSONRPC)
//main loops
if len(cfg.PortSSL) > 0 {
tlsConfig := &tls.Config{}
tlsConfig.Certificates = make([]tls.Certificate, 1)
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(cfg.SSLCert, cfg.SSLKey)
if err != nil {
log.Fatal(err)
}
tlsConfig.BuildNameToCertificate()
listener, err := tls.Listen("tcp", ":"+cfg.PortSSL, tlsConfig)
if err != nil {
log.Fatal(err)
}
go func() {
log.Fatal(fasthttp.Serve(listener, router.Handler))
}()
}
listener, err := net.Listen("tcp", ":"+cfg.Port)
if err != nil {
log.Fatal(err)
}
log.Fatal(fasthttp.Serve(listener, router.Handler))
}