lego_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package test
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "testing"
  11. "github.com/go-acme/lego/v4/certcrypto"
  12. "github.com/go-acme/lego/v4/certificate"
  13. "github.com/go-acme/lego/v4/challenge/http01"
  14. "github.com/go-acme/lego/v4/lego"
  15. "github.com/go-acme/lego/v4/registration"
  16. )
  17. // You'll need a user or account type that implements acme.User
  18. type MyUser struct {
  19. Email string
  20. Registration *registration.Resource
  21. key crypto.PrivateKey
  22. }
  23. func (u *MyUser) GetEmail() string {
  24. return u.Email
  25. }
  26. func (u MyUser) GetRegistration() *registration.Resource {
  27. return u.Registration
  28. }
  29. func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
  30. return u.key
  31. }
  32. func TestLego(t *testing.T) {
  33. // Create a user. New accounts need an email and private key to start.
  34. privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  35. if err != nil {
  36. log.Fatal(err)
  37. }
  38. myUser := MyUser{
  39. Email: "me@jackyu.cn",
  40. key: privateKey,
  41. }
  42. config := lego.NewConfig(&myUser)
  43. // This CA URL is configured for a local dev instance of Boulder running in Dockerfile in a VM.
  44. config.CADirURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
  45. config.Certificate.KeyType = certcrypto.RSA2048
  46. // A client facilitates communication with the CA server.
  47. client, err := lego.NewClient(config)
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", "9180"))
  52. if err != nil {
  53. log.Fatal(err)
  54. }
  55. // New users will need to register
  56. reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  57. if err != nil {
  58. log.Fatal(err)
  59. }
  60. myUser.Registration = reg
  61. request := certificate.ObtainRequest{
  62. Domains: []string{"shanghai2.ojbk.me"},
  63. Bundle: true,
  64. }
  65. certificates, err := client.Certificate.Obtain(request)
  66. if err != nil {
  67. log.Fatal(err)
  68. }
  69. // Each certificate comes back with the cert bytes, the bytes of the client's
  70. // private key, and a certificate URL. SAVE THESE TO DISK.
  71. fmt.Printf("%#v\n", certificates)
  72. err = ioutil.WriteFile("fullchain.cer", certificates.Certificate, 0644)
  73. if err != nil {
  74. log.Fatal(err)
  75. }
  76. err = ioutil.WriteFile("private.key", certificates.PrivateKey, 0644)
  77. if err != nil {
  78. log.Fatal(err)
  79. }
  80. }