view cmd/tokenserver/main.go @ 196:b67208d82543

Make test output more comprehensive Running all tests in one transaction ensures the final output tells about any failing test, not just in the last transaction (i.e. test script). The price is that no traces of the tests are left in the database because we have to rollback in order to have no left-over test roles in the cluster.
author Tom Gottfried <tom@intevation.de>
date Fri, 20 Jul 2018 18:31:45 +0200
parents fe3a88f00b0a
children
line wrap: on
line source

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"

	"gemma.intevation.de/gemma/auth"
)

func sysAdmin(rw http.ResponseWriter, req *http.Request) {
	session, _ := auth.GetSession(req)
	rw.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(rw, "%s is a sys_admin\n", session.User)
}

func main() {
	port := flag.Int("port", 8000, "port to listen at.")
	host := flag.String("host", "localhost", "host to listen at.")
	flag.Parse()
	p, _ := filepath.Abs("./web")
	mux := http.NewServeMux()
	mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(p))))
	mux.HandleFunc("/api/token", token)
	mux.Handle("/api/logout", auth.SessionMiddleware(http.HandlerFunc(token)))
	mux.Handle("/api/renew", auth.SessionMiddleware(http.HandlerFunc(renew)))
	mux.Handle("/api/sys_admin",
		auth.SessionMiddleware(
			auth.SessionChecker(http.HandlerFunc(sysAdmin), auth.HasRole("sys_admin"))))
	mux.Handle("/api/create_user",
		auth.SessionMiddleware(
			auth.SessionChecker(http.HandlerFunc(createUser), auth.HasRole("sys_admin"))))

	addr := fmt.Sprintf("%s:%d", *host, *port)

	server := http.Server{Addr: addr, Handler: mux}

	done := make(chan error)

	go func() {
		defer close(done)
		done <- server.ListenAndServe()
	}()

	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, os.Interrupt, os.Kill, syscall.SIGTERM)

	select {
	case err := <-done:
		if err != nil && err != http.ErrServerClosed {
			log.Fatalf("error: %v\n", err)
		}
	case <-sigChan:
	}

	server.Shutdown(context.Background())

	<-done

	if err := auth.ConnPool.Shutdown(); err != nil {
		log.Fatalf("error: %v\n", err)
	}
}