github.com/qichengzx/mattermost-server@v4.5.1-0.20180604164826-2c75247c97d0+incompatible/plugin/example_hello_user_test.go (about)

     1  package plugin_test
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/mattermost/mattermost-server/plugin"
     8  	"github.com/mattermost/mattermost-server/plugin/rpcplugin"
     9  )
    10  
    11  type HelloUserPlugin struct {
    12  	api plugin.API
    13  }
    14  
    15  func (p *HelloUserPlugin) OnActivate(api plugin.API) error {
    16  	// Just save api for later when we need to look up users.
    17  	p.api = api
    18  	return nil
    19  }
    20  
    21  func (p *HelloUserPlugin) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    22  	if userId := r.Header.Get("Mattermost-User-Id"); userId == "" {
    23  		// Our visitor is unauthenticated.
    24  		fmt.Fprintf(w, "Hello, stranger!")
    25  	} else if user, err := p.api.GetUser(userId); err == nil {
    26  		// Greet the user by name!
    27  		fmt.Fprintf(w, "Welcome back, %v!", user.Username)
    28  	} else {
    29  		// This won't happen in normal circumstances, but let's just be safe.
    30  		w.WriteHeader(http.StatusInternalServerError)
    31  		fmt.Fprintf(w, err.Error())
    32  	}
    33  }
    34  
    35  // This example demonstrates a plugin that handles HTTP requests which respond by greeting the user
    36  // by name.
    37  func Example_helloUser() {
    38  	rpcplugin.Main(&HelloUserPlugin{})
    39  }