summaryrefslogtreecommitdiff
path: root/cmd/dolmetschctld/web.go
blob: ad42429b9fc41ecb616c9fc8d309222593f4a6a8 (plain) (blame)
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
//
//  dolmetschctl
//
//
//  Copyright (C) 2019 Christian Pointner <equinox@spreadspace.org>
//
//  This file is part of dolmetschctl.
//
//  dolmetschctl is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  dolmetschctl is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with dolmetschctl. If not, see <http://www.gnu.org/licenses/>.
//

package main

import (
	"encoding/json"
	"net/http"
	"time"
)

type WebInterface struct {
	server *http.Server
}

type webHandler struct {
	sm *StateMachine
	H  func(*StateMachine, http.ResponseWriter, *http.Request)
}

func (self webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	self.H(self.sm, w, r)
}

func webSendResponse(w http.ResponseWriter, status int, respdata interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	encoder := json.NewEncoder(w)
	encoder.Encode(respdata)
}

type webError struct {
	ResponseCode int    `json:"response-code"`
	Error        string `json:"error"`
}

func webSendErrorResponse(w http.ResponseWriter, status int, error string) {
	webSendResponse(w, status, webError{ResponseCode: status, Error: error})
}

type webState struct {
	State State    `json:"state"`
	Ratio float32  `json:"original-to-interpreter-ratio"`
	Lang  Language `json:"language"`
}

func webGetStateHandler(sm *StateMachine, w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		webSendErrorResponse(w, http.StatusMethodNotAllowed, "only GET method is allowed")
		return
	}

	var result webState
	result.State, result.Ratio, result.Lang = sm.GetState()
	webSendResponse(w, http.StatusOK, result)
}

func (web *WebInterface) Run() error {
	return web.server.ListenAndServe()
}

func NewWebInterface(addr string, sm *StateMachine) (web *WebInterface, err error) {
	web = &WebInterface{}

	http.Handle("/api/v1/state", webHandler{sm, webGetStateHandler})
	// TODO: add other handler

	web.server = &http.Server{Addr: addr, ReadTimeout: 2 * time.Hour, WriteTimeout: 2 * time.Hour}
	return
}