69 lines
1.8 KiB
Go
69 lines
1.8 KiB
Go
package plugin
|
|
|
|
import (
|
|
"encoding/json"
|
|
"github.com/gorilla/mux"
|
|
"github.com/mattermost/mattermost/server/public/plugin"
|
|
"net/http"
|
|
"path/filepath"
|
|
)
|
|
|
|
type httpResponse struct {
|
|
Status string `json:"status"`
|
|
Error string `json:"error,omitempty"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
}
|
|
|
|
func (p *Plugin) sendError(w http.ResponseWriter, err string) {
|
|
errEnc := json.NewEncoder(w).Encode(httpResponse{
|
|
Status: "error",
|
|
Error: err,
|
|
})
|
|
if errEnc != nil {
|
|
p.API.LogError("cant encode error response", "error", errEnc)
|
|
}
|
|
}
|
|
|
|
func (p *Plugin) sendRes(w http.ResponseWriter, resp httpResponse) {
|
|
errEnc := json.NewEncoder(w).Encode(resp)
|
|
if errEnc != nil {
|
|
p.API.LogError("cant encode error response", "error", errEnc)
|
|
}
|
|
}
|
|
|
|
func (p *Plugin) InitApi() {
|
|
p.router = mux.NewRouter()
|
|
|
|
p.router.Use(func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if userID := r.Header.Get("Mattermost-User-Id"); userID != "" {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
http.Error(w, "Not authorized", http.StatusUnauthorized)
|
|
})
|
|
})
|
|
|
|
// Add your API routes here
|
|
p.router.HandleFunc("/example", p.handleExample).Methods("GET")
|
|
p.router.HandleFunc("/assets/{fileName}", p.handleAssetFile).Methods("GET")
|
|
}
|
|
|
|
func (p *Plugin) ServeHTTP(_ *plugin.Context, w http.ResponseWriter, r *http.Request) {
|
|
p.router.ServeHTTP(w, r)
|
|
}
|
|
|
|
func (p *Plugin) handleAssetFile(w http.ResponseWriter, r *http.Request) {
|
|
fileName := mux.Vars(r)["fileName"]
|
|
http.ServeFile(w, r, filepath.Join(p.bundlePath, "assets", fileName))
|
|
}
|
|
|
|
func (p *Plugin) handleExample(w http.ResponseWriter, r *http.Request) {
|
|
p.sendRes(w, httpResponse{
|
|
Status: "OK",
|
|
Data: map[string]interface{}{
|
|
"message": "Hello from template plugin",
|
|
},
|
|
})
|
|
}
|