- Learning Functional Programming in Go
- Lex Sheehan
- 268字
- 2021-07-02 23:13:53
The main.go file
Let's have a look at the contents of main.go:
package main
import (
"crypto/tls"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"time"
"easy_metrics"
. "decorator"
)
const (
host = "127.0.0.1"
protocol = "http://"
)
var (
serverUrl string
proxyUrl string
)
This is what the imports looked like before using the init script and its aliases (and glide):
import (
. . .
"time"
"github.com/l3x/fp-in-go/chapter5/02_decorator/easy_metrics"
. "github.com/l3x/fp-in-go/chapter5/02_decorator"
)
I never liked long repository paths in my imports. I suppose it's time to give this technique a name. Let's call it Dot Init script (. init).
We define a host as a constant because we will always run this example code on our local workstation. We'll keep things simple and use the HTTP protocol (no SSL).
Our example uses a proxy server and also uses Go's standard library HTTP server implementation to listen to handle requests:
![](https://epubservercos.yuewen.com/6176FA/19470400908922906/epubprivate/OEBPS/Images/Chapter_193.jpg?sign=1739054451-QMYlHPAo3QEhalisCd3ddVKNE1D3200p-0-0beeec4a620fa8853725d7e7bb189022)
Any function named init() will be executed before the main() function. We define default port numbers for our two servers and permit the user to specify different ports at runtime using the flag package, which implements command-line flag parsing:
func init() {
serverPort := 3000
proxyPort := 8080
flag.IntVar(&serverPort, "serverPort", serverPort, "Server Port")
flag.IntVar(&proxyPort, "proxyPort", proxyPort, "Server Port")
flag.Parse()
serverUrl = fmt.Sprintf("%s:%d", host, serverPort)
proxyUrl = fmt.Sprintf("%s:%d", host, proxyPort)
}
Simple Logger
We'll implement a simple logger that will:
- Provide log file tracing
- Provide Debug, Info, and Error log levels
- Permit us to specify which log level(s) we want
- Enable us to more easily swap out our underlying logging framework