Private
Public Access
1
0
Files
Kordophone/web/server.go

57 lines
1.3 KiB
Go
Raw Normal View History

package web
import (
"encoding/json"
"fmt"
"log"
"net/http"
"code.severnaya.net/kordophone-mock/v2/server"
)
type MockHTTPServer struct {
Server server.Server
mux http.ServeMux
}
func (m *MockHTTPServer) handleVersion(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", m.Server.Version())
}
func (m *MockHTTPServer) handleStatus(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "OK")
}
func (m *MockHTTPServer) handleConversations(w http.ResponseWriter, r *http.Request) {
convos := m.Server.Conversations()
// Encode convos as JSON
jsonData, err := json.Marshal(convos)
if err != nil {
log.Printf("Error marshalling conversations: %s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write JSON to response
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func (m *MockHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.mux.ServeHTTP(w, r)
}
func NewMockHTTPServer() *MockHTTPServer {
this := MockHTTPServer{
Server: *server.NewServer(),
mux: *http.NewServeMux(),
}
this.mux.Handle("/version", http.HandlerFunc(this.handleVersion))
this.mux.Handle("/conversations", http.HandlerFunc(this.handleConversations))
this.mux.Handle("/status", http.HandlerFunc(this.handleStatus))
return &this
}