Skip to content

Instantly share code, notes, and snippets.

@samthor
Last active April 15, 2024 15:47
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save samthor/5ff8cfac1f80b03dfe5a9be62b29d7f2 to your computer and use it in GitHub Desktop.
Save samthor/5ff8cfac1f80b03dfe5a9be62b29d7f2 to your computer and use it in GitHub Desktop.
Demo autocert server in Go
package main
import (
"crypto/tls"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/user"
"path/filepath"
"golang.org/x/crypto/acme/autocert"
)
func main() {
// setup a simple handler which sends a HTHS header for six months (!)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=15768000 ; includeSubDomains")
fmt.Fprintf(w, "Hello, HTTPS world!")
})
// look for the domains to be served from command line args
flag.Parse()
domains := flag.Args()
if len(domains) == 0 {
log.Fatalf("fatal; specify domains as arguments")
}
// create the autocert.Manager with domains and path to the cache
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(domains...),
}
// optionally use a cache dir
dir := cacheDir()
if dir != "" {
certManager.Cache = autocert.DirCache(dir)
}
// create the server itself
server := &http.Server{
Addr: ":https",
TLSConfig: &tls.Config{
GetCertificate: certManager.GetCertificate,
},
}
log.Printf("Serving http/https for domains: %+v", domains)
go func() {
// serve HTTP, which will redirect automatically to HTTPS
h := certManager.HTTPHandler(nil)
log.Fatal(http.ListenAndServe(":http", h))
}()
// serve HTTPS!
log.Fatal(server.ListenAndServeTLS("", ""))
}
// cacheDir makes a consistent cache directory inside /tmp. Returns "" on error.
func cacheDir() (dir string) {
if u, _ := user.Current(); u != nil {
dir = filepath.Join(os.TempDir(), "cache-golang-autocert-"+u.Username)
if err := os.MkdirAll(dir, 0700); err == nil {
return dir
}
}
return ""
}
@suntong
Copy link

suntong commented May 7, 2019

Hi, when I try it, I'm getting the following errors:

autocert-server.go:18:75: missing ',' before newline in argument list
autocert-server.go:19:100: missing ',' before newline in argument list
autocert-server.go:20:54: missing ',' before newline in argument list
autocert-server.go:21:9: expected operand, found '}'
autocert-server.go:26:9: missing ',' in argument list
autocert-server.go:27:66: missing ',' before newline in argument list
autocert-server.go:28:9: expected operand, found '}'
autocert-server.go:38:9: missing ',' in argument list
autocert-server.go:39:35: expected '==', found '='
autocert-server.go:40:9: expected operand, found '}'
autocert-server.go:51:9: missing ',' in argument list

Would you be so kind to fix it pls? thx

@shadow1163
Copy link

Hi, when I try it, I'm getting the following errors:

autocert-server.go:18:75: missing ',' before newline in argument list
autocert-server.go:19:100: missing ',' before newline in argument list
autocert-server.go:20:54: missing ',' before newline in argument list
autocert-server.go:21:9: expected operand, found '}'
autocert-server.go:26:9: missing ',' in argument list
autocert-server.go:27:66: missing ',' before newline in argument list
autocert-server.go:28:9: expected operand, found '}'
autocert-server.go:38:9: missing ',' in argument list
autocert-server.go:39:35: expected '==', found '='
autocert-server.go:40:9: expected operand, found '}'
autocert-server.go:51:9: missing ',' in argument list

Would you be so kind to fix it pls? thx

you can add "{" in end of line 18. It should work.

@samthor
Copy link
Author

samthor commented Aug 1, 2019

Sorry, I must have accidentally deleted that character when I uploaded this. It's fixed now 👍

If you're curious, I wrote I forwarding server using this autocert stuff, so you can host "dumb" HTTP services online with HTTPS: https://github.com/samthor/https-forward

@arshpreetsingh
Copy link

arshpreetsingh commented Jun 26, 2022

Hey @samthor does it work on localhost as well?

go run autocert-server.com localhost

I am not able to get certificate for that.
Or will it be possible to make work on Localhost?

@Plaenkler
Copy link

@arshpreetsingh If you want to run your application locally you should use a self signed certificate.
Check this out -> https://pkg.go.dev/crypto/x509

@jesson3264
Copy link

How to test? Why I enter http://xyzabc.com in browser, It not show any something right.
I have configured a domain in host file.

127.0.0.1 xyzabc.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment