package main import ( "bufio" "bytes" "crypto/tls" "crypto/x509" "encoding/json" "fmt" "io" "log" "net/http" "os" ) type HttpServer struct { Port string ovpn *OpenVpnMgt key string cert string certPool *x509.CertPool } func (h *HttpServer) handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) } func (h *HttpServer) versionHandler(w http.ResponseWriter, r *http.Request) { err, message := h.ovpn.Version() if err != nil { fmt.Fprintf(w, "Error : %s", err) } jsonStr, err := json.Marshal(message) if err != nil { fmt.Fprintf(w, "Error : %s", err) } fmt.Fprintf(w, "%s", jsonStr) } func (h *HttpServer) helpHandler(w http.ResponseWriter, r *http.Request) { err, message := h.ovpn.Help() if err != nil { fmt.Fprintf(w, "Error : %s", err) } jsonStr, err := json.Marshal(message) if err != nil { fmt.Fprintf(w, "Error : %s", err) } fmt.Fprintf(w, "%s", jsonStr) } func NewHTTPServer(port, key, cert, ca string, s *OpenVpnMgt) { h := &HttpServer{ Port: port, ovpn: s, key: key, cert: cert, } http.HandleFunc("/help", h.helpHandler) http.HandleFunc("/version", h.versionHandler) http.HandleFunc("/", h.handler) switch { case key == "" || cert == "": log.Fatal(http.ListenAndServe(port, nil)) case ca != "": h.certPool = x509.NewCertPool() fi, err := os.Open(ca) if err != nil { log.Fatal(err) } defer fi.Close() buf := new(bytes.Buffer) reader := bufio.NewReader(fi) io.Copy(buf, reader) if ok := h.certPool.AppendCertsFromPEM(buf.Bytes()); !ok { log.Fatal("Failed to append PEM.") } server := &http.Server{ Addr: port, TLSConfig: &tls.Config{ ClientAuth: tls.RequestClientCert, ClientCAs: h.certPool, }, } log.Fatal(server.ListenAndServeTLS(cert, key)) default: log.Fatal(http.ListenAndServeTLS(port, cert, key, nil)) } }