github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/command/testdata/login-tfe-server/tfeserver.go (about)

     1  // Package tfeserver is a test stub implementing a subset of the TFE API used
     2  // only for the testing of the "terraform login" command.
     3  package tfeserver
     4  
     5  import (
     6  	"fmt"
     7  	"net/http"
     8  	"strings"
     9  )
    10  
    11  const (
    12  	goodToken      = "good-token"
    13  	accountDetails = `{"data":{"id":"user-abc123","type":"users","attributes":{"username":"testuser","email":"testuser@example.com"}}}`
    14  )
    15  
    16  // Handler is an implementation of net/http.Handler that provides a stub
    17  // TFE API server implementation with the following endpoints:
    18  //
    19  //     /ping            - API existence endpoint
    20  //     /account/details - current user endpoint
    21  var Handler http.Handler
    22  
    23  type handler struct{}
    24  
    25  func (h handler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
    26  	resp.Header().Set("Content-Type", "application/vnd.api+json")
    27  	switch req.URL.Path {
    28  	case "/api/v2/ping":
    29  		h.servePing(resp, req)
    30  	case "/api/v2/account/details":
    31  		h.serveAccountDetails(resp, req)
    32  	default:
    33  		fmt.Printf("404 when fetching %s\n", req.URL.String())
    34  		http.Error(resp, `{"errors":[{"status":"404","title":"not found"}]}`, http.StatusNotFound)
    35  	}
    36  }
    37  
    38  func (h handler) servePing(resp http.ResponseWriter, req *http.Request) {
    39  	resp.WriteHeader(http.StatusNoContent)
    40  }
    41  
    42  func (h handler) serveAccountDetails(resp http.ResponseWriter, req *http.Request) {
    43  	if !strings.Contains(req.Header.Get("Authorization"), goodToken) {
    44  		http.Error(resp, `{"errors":[{"status":"401","title":"unauthorized"}]}`, http.StatusUnauthorized)
    45  		return
    46  	}
    47  
    48  	resp.WriteHeader(http.StatusOK)
    49  	resp.Write([]byte(accountDetails))
    50  }
    51  
    52  func init() {
    53  	Handler = handler{}
    54  }