go-totp/main.go

50 lines
1017 B
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"text/template"
"time"
"github.com/xlzd/gotp"
)
var addr = "0.0.0.0:8080"
type secret struct {
S string `json:"secret"`
}
type code struct {
C string `json:"code"`
T int `json:"time"`
}
func calculate(w http.ResponseWriter, r *http.Request) {
var s secret
json.NewDecoder(r.Body).Decode(&s)
totp := gotp.NewDefaultTOTP(s.S).Now()
c := &code{
C: totp,
T: int(30 - time.Now().Unix()%30),
}
response, _ := json.Marshal(c)
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
func index(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("templates/index.html")
t.Execute(w, nil)
}
func main() {
staticFolder := http.FileServer(http.Dir("./static"))
http.HandleFunc("/", index)
http.HandleFunc("/calculate", calculate)
http.Handle("/static/", http.StripPrefix(strings.TrimRight("/static/", "/"), staticFolder))
fmt.Println("Listening on ", addr)
http.ListenAndServe(addr, nil)
}