...

Source file src/github.com/palantir/go-baseapp/example/main.go

Documentation: github.com/palantir/go-baseapp/example

     1  // Copyright 2018 Palantir Technologies, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"net/http"
    19  
    20  	"github.com/palantir/go-baseapp/baseapp"
    21  	"github.com/palantir/go-baseapp/baseapp/datadog"
    22  	"github.com/rs/zerolog"
    23  	"goji.io/pat"
    24  )
    25  
    26  type MessageHandler struct {
    27  	Message string
    28  }
    29  
    30  func (h *MessageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    31  	ctx := r.Context()
    32  	logger := zerolog.Ctx(ctx)
    33  
    34  	// Logging example
    35  	logger.Info().Str("user-agent", r.Header.Get("User-Agent")).Msg("Received request")
    36  
    37  	baseapp.WriteJSON(w, http.StatusOK, map[string]string{
    38  		"message": h.Message,
    39  	})
    40  }
    41  
    42  // type assertion
    43  var _ http.Handler = &MessageHandler{}
    44  
    45  func main() {
    46  	// Load your configuration from a file
    47  	config, err := ReadConfig("example/config.yml")
    48  	if err != nil {
    49  		panic(err)
    50  	}
    51  
    52  	// Configure a root logger for everything to use
    53  	logger := baseapp.NewLogger(config.Logging)
    54  
    55  	// Create a server using the default options
    56  	serverParams := baseapp.DefaultParams(logger, "example.")
    57  	server, err := baseapp.NewServer(config.Server, serverParams...)
    58  	if err != nil {
    59  		panic(err)
    60  	}
    61  
    62  	// Register your routes with the server
    63  	messageHandler := &MessageHandler{Message: config.App.Message}
    64  	server.Mux().Handle(pat.Get("/api/message"), messageHandler)
    65  
    66  	// Start a goroutine to emit server metrics to Datadog
    67  	if err := datadog.StartEmitter(server, config.Datadog); err != nil {
    68  		panic(err)
    69  	}
    70  
    71  	// Start the server (blocking)
    72  	_ = server.Start()
    73  }
    74  

View as plain text