summaryrefslogtreecommitdiffstats
path: root/plugin/example_hooks_test.go
blob: 7ca1cf5f09047f8c5278d880160cd58eb1d7d032 (plain)
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
package plugin_test

import (
	"fmt"
	"net/http"

	"github.com/mattermost/mattermost-server/plugin"
	"github.com/mattermost/mattermost-server/plugin/rpcplugin"
)

type MyPlugin struct {
	api plugin.API
}

func (p *MyPlugin) OnActivate(api plugin.API) {
	// Just save api for later when we need to look up users.
	p.api = api
}

func (p *MyPlugin) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if userId := r.Header.Get("Mattermost-User-Id"); userId == "" {
		// Our visitor is unauthenticated.
		fmt.Fprintf(w, "Hello, stranger!")
	} else if user, err := p.api.GetUser(userId); err == nil {
		// Greet the user by name!
		fmt.Fprintf(w, "Welcome back, %v!", user.Username)
	} else {
		// This won't happen in normal circumstances, but let's just be safe.
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, err.Error())
	}
}

// This example demonstrates a plugin that handles HTTP requests which respond by greeting the user
// by name.
func Example_plugin() {
	rpcplugin.Main(&MyPlugin{})
}