File: api.go

package info (click to toggle)
golang-github-xenolf-lego 4.9.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,080 kB
  • sloc: xml: 533; makefile: 128; sh: 18
file content (66 lines) | stat: -rw-r--r-- 1,596 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package tester

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/go-acme/lego/v4/acme"
)

// SetupFakeAPI Minimal stub ACME server for validation.
func SetupFakeAPI(t *testing.T) (*http.ServeMux, string) {
	t.Helper()

	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	t.Cleanup(server.Close)

	mux.HandleFunc("/dir", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
			return
		}

		err := WriteJSONResponse(w, acme.Directory{
			NewNonceURL:   server.URL + "/nonce",
			NewAccountURL: server.URL + "/account",
			NewOrderURL:   server.URL + "/newOrder",
			RevokeCertURL: server.URL + "/revokeCert",
			KeyChangeURL:  server.URL + "/keyChange",
		})

		mux.HandleFunc("/nonce", func(w http.ResponseWriter, r *http.Request) {
			if r.Method != http.MethodHead {
				http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
				return
			}

			w.Header().Set("Replay-Nonce", "12345")
			w.Header().Set("Retry-After", "0")
		})

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})

	return mux, server.URL
}

// WriteJSONResponse marshals the body as JSON and writes it to the response.
func WriteJSONResponse(w http.ResponseWriter, body interface{}) error {
	bs, err := json.Marshal(body)
	if err != nil {
		return err
	}

	w.Header().Set("Content-Type", "application/json")
	if _, err := w.Write(bs); err != nil {
		return err
	}

	return nil
}