github.com/eliastor/durgaform@v0.0.0-20220816172711-d0ab2d17673e/internal/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 "durgaform 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 MOTD = `{"msg":"Welcome to Durgaform Cloud!"}` 15 ) 16 17 // Handler is an implementation of net/http.Handler that provides a stub 18 // TFE API server implementation with the following endpoints: 19 // 20 // /ping - API existence endpoint 21 // /account/details - current user endpoint 22 var Handler http.Handler 23 24 type handler struct{} 25 26 func (h handler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { 27 resp.Header().Set("Content-Type", "application/vnd.api+json") 28 switch req.URL.Path { 29 case "/api/v2/ping": 30 h.servePing(resp, req) 31 case "/api/v2/account/details": 32 h.serveAccountDetails(resp, req) 33 case "/api/durgaform/motd": 34 h.serveMOTD(resp, req) 35 default: 36 fmt.Printf("404 when fetching %s\n", req.URL.String()) 37 http.Error(resp, `{"errors":[{"status":"404","title":"not found"}]}`, http.StatusNotFound) 38 } 39 } 40 41 func (h handler) servePing(resp http.ResponseWriter, req *http.Request) { 42 resp.WriteHeader(http.StatusNoContent) 43 } 44 45 func (h handler) serveAccountDetails(resp http.ResponseWriter, req *http.Request) { 46 if !strings.Contains(req.Header.Get("Authorization"), goodToken) { 47 http.Error(resp, `{"errors":[{"status":"401","title":"unauthorized"}]}`, http.StatusUnauthorized) 48 return 49 } 50 51 resp.WriteHeader(http.StatusOK) 52 resp.Write([]byte(accountDetails)) 53 } 54 55 func (h handler) serveMOTD(resp http.ResponseWriter, req *http.Request) { 56 resp.WriteHeader(http.StatusOK) 57 resp.Write([]byte(MOTD)) 58 } 59 60 func init() { 61 Handler = handler{} 62 }