go-totp/main.go

48 lines
1010 B
Go
Raw Normal View History

2020-09-15 07:48:54 +00:00
package main
import (
"fmt"
"encoding/json"
"net/http"
"strings"
"text/template"
"time"
"github.com/xlzd/gotp"
)
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 127.0.0.1:8000")
http.ListenAndServe("127.0.0.1:8000", nil)
}